Using Microsoft.Identity.Web to authenticate users for WebApp+API, and how to manage lifecycle - asp.net-core

I'm trying to create a webapp that uses multi-tenant Azure AD for authentication & authorization. I'm trying to follow the docs, using Microsoft.Identity.Web, and the pieces aren't clicking for me.
I've been able to successfully create a web app where users are able to login, get redirected back to my site, and get an id_token saved to their browser cookies so the web app is able to tell who they are. However, my web app also contains APIs itself, and it isn't clear to me how we're supposed to obtain an access_token, as well as manage the lifecycle by way of refresh_tokens, for calling APIs on the web app itself. In fact, refresh doesn't seem to be covered at all in the docs for Microsoft.Identity.Web.
Instead of the dedicated SDK, I've also tried using AddCookie()+AddOpenIdConnect() (the more generic solution). Using these middleware options I've successfully been able to obtain an id_token, access_token, and refresh_token. (Which seems to connect all the pieces of access, and refresh/lifecycle.) However, all of those tokens take up a fair amount of cookie space, and cause 431 Request Header Fields Too Large errors from Kestrel without customization.
It's clear that the intention is for access/refresh tokens to be stored server-side on some sort of in-memory or distributed cache. However, the documentation doesn't seem to outline how to deal with "web apps" that ALSO contain API controllers, and furthermore doesn't seem to outline how to deal with token refreshes in general.
Does anyone have any better in-code examples of how to configure a WebApp that authenticates users with Azure AD, and also properly handles refreshing the id/access tokens using the refresh_token?

Refresh tokens are automatically handled by MSAL.NET, which is used by Microsoft.Identity.Web.
We suggest you have a look at the following sample: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/4-WebApp-your-API/4-3-AnyOrg but you would have the same clientID (and app) for your web app and web API.
Please also look at https://github.com/AzureAD/microsoft-identity-web/wiki/Mixing-web-app-and-web-api-in-the-same-ASP.NET-core-app

Related

How to use Google APIs without continuously explicit user consent from a progressive web application?

I have a progressive web application that needs write-access to the Google Drive API for uploading data (media files) the user is creating (either online or offline) in the background while online. It does not really need a server (except for serving the required files, so a static server is sufficient), all of the work could be done on the web application client side.
Since uploading needs to happen on the background, whenever the user is online again (using a service worker and the background sync one-shot API), an access token is not enough for my need (the user can be offline/not use the web application for days) and a refresh token is not supposed to be stored on the web application client side, as far as I understand. Even if it were, I would still need the client secret, which means I have to use a server (or keep the secret within the web application client side, which is a no-no) in order to refresh the token.
It seems like the current ways of using the OAuth2 scheme are at odds with server-less progressive web applications, or I might be missing something. Progressive web applications are more like Chrome applications in this regard, I guess, but I have to supply a Chrome application ID in the Google API console for my application, which I do not (and do not intend to) have and Chrome applications use the Chrome identity API for getting the tokens, which I do not intend to use (and cannot).
I am currently using an actual Node.js server which takes care of the authorization step, keeps the access token and refresh token in a database and returns the existing or new access token to the client, whenever asked. The server is redundant here (and requires a privacy policy for this data which I really do not need to store), I want to do everything using client code, without continuously asking for authorization whenever I upload in the background.
Keeping the refresh token on the web application client side and just reaching out to the server for actually refreshing the access token (nothing must be stored in the server side except the client secret, which is fine), but like I mentioned, I understand the refresh token is not supposed to be kept on the web application side.
Is there a safe and secure way to implement this without a server (or with a server that only gets the refresh token and returns it to the client and refreshes the access token by getting the refresh token from the client)?
It's actually fairly simple, depending on the fine details of your use case.
An important factoid is that once a user has granted permission to your app, he will not have to re-grant it. So you don't need to "continuously asking for authorization whenever I upload in the background". However, the only constraint is that the user must be logged in to Google in order to obtain an Access Token. Normally this isn't an issue, but your app needs to deal with the scenario that a user has logged off from Google, and prompt for login.
All the details are here https://developers.google.com/identity/protocols/OAuth2UserAgent
I suggest avoid the Google JS library because (a) it has its own opinions about the UX, (b) wasn't written with PWAs in mind, (c) has issues on mobile, and (d) is closed source so when it breaks (as it does occasionally), your users are dead in the water until Google fixes it. The page above details the OAuth endpoints so you can easily use them directly. This has the side benefit that adding other cloud storage accounts (AWS, Azure, Drop, etc) is just a case of changing the endpoint URL.
The architecture I use in my PWA is to have my PWA prompt once (and once only) for authorization and then store the user's Gmail address in localStorage. I then have a
hidden iframe which polls once per hour for an Access Token, using the gmail address in a login_hint. This means the iframe is never required to present any UX. The only time UX is required is for the initial auth, which is of course unavoidable, and once per session if the user has logged out of Google.
The only other edge-case you might want to deal with is allowing the user to select between multiple Google accounts, say a personal account and a work domain account.
On a broader point, remember that Google didn't create the OAuth spec so there is little they can do to provide an alternative solution. At an abstract level, auth requires one of the user being present, or secure storage for a permanent token (eg on a server or within a secure store such as Android). Even if we invent OAuth 3, that will still be the case.

IdentityServer4 External Authentication without cookies

I'm having trouble understanding how ASP.NET Core authentication works.
I want to implement JWT access token authentication with refresh tokens. To my knowledge, this is the industry standard for authenticating a client (Mobile app, SPA Web application). For security purposes, I'd prefer to not implement my own authorization logic including JWT generation and refresh token handling. Since ASP.Net does not natively support this, Naturally my choice would be to use IdentityServer4, a large open source library for handling this kind of stuff.
However IdentityServer4 is heavily based on OAuth, and I'm not sure how that works with SPA applications and mobile apps (clients I trust). It requires the client to redirect to some arbitrary webpage to enter their credentials and then redirect back to the app. Gross. I've never seen a major app like Snapchat, Instagram, etc. have this kind of authentication flow where you are directed to some webpage/browser during the login flow. Luckily IdentityServer4 has a little feature to handle username/password authentication for my trusted clients (http://docs.identityserver.io/en/latest/quickstarts/2_resource_owner_passwords.html)
Great, that seems to suit my needs. But... Now I want to add Facebook Authentication. IdentityServer4 allows for External Authentication, however it is still cookie based (to my knowledge). Which requires the Android/iOS/SPA app to redirect to a webpage and then redirect back to the app. Again, this isn't ideal from a user perspective. Facebook provides native mobile SDKs to handle this type of authentication which returns an access token so there is no need to redirect to web pages using cookies.
Now lets say my iOS app uses the Facebook SDK to grab an access token for the user and sends it to the backend. The backend validates the token against the Facebook SDK, and subsequently registers a local user in it's own database.
Now when that same iOS user tries to login to the app, the app will generate a facebook access token for that user from the SDK and send it to the backend. However I'm not sure how to utilize IdentityServer4 to generate a JWT for the user since I need that users' username and password. This is where I'm stuck. I seem to be fighting against the library which makes me believe I am severely misunderstanding something.
TLDR; IdentityServer4 seems to be heavily based on cookies which doesn't really fit nicely into mobile apps/SPA webpages when you are redirected back and forth from authentication webpages. Am I using the wrong tool for the job? What are some alternative solutions?
As a note on big social apps: I think it comes down to who keeps the passwords. Facebook, Instagram, Snapchat, Google act as identity providers to third parties. They themselves require user to register and specify the password which they keep. Therefore they can use any customized approach for handling validation with those passwords. However, if any of them offerred a posibiltty to log-in with the other I.e Instagram were allowing to sign-in with Amazon credentials, then they would need to follow through a standard way like OAuth and redirect to the third party for log-in. Last time I checked Instagram, Facebook and Snapchat only offer to register and no option to sign in with 3rd parties which explains why the don't need redirects.
Now if we establish that a redirect is a necessary evil, then the means to carry over the data accross aren't that numerous. I.e. we either would need to pass data via a query string or use cookies. Am I missing any others?
Both have limitations but since cookies are persisted and browser carries them automatically with each request, they do seem like a better option for the job, especially if multiple redirects are required for an external IdP to track the state of authentication request. The same reason is mentioned here:
http://docs.identityserver.io/en/latest/topics/signin_external_providers.html
It's absolutely the right tool for the job if you want what OpenID Connect and OAuth2 give you. It sounds like you may need convincing though and it may be that your use case doesn't need the full breadth of functionality offered.
If you have multiple client applications and APIs in play then I think using OpenID Connect and IdentityServer4 the right choice at this point in time.
Regarding native apps, you used to word "gross" to describe using the user's default browser to perform the sign in process and it's understandable why you might think that at first but it's not as bad of a UX as you'd think and has plenty of advantages:
The client application is completely decoupled from how authentication is actually done be that federation, social sign in (Facebook in your case), multi-factor, retina scan etc. Your identity server deals with all that complexity and is a single point of management (and failure - so make it highly available!)
Single sign on is possible - if they're already signed into your IDP then they can go straight in (although you have full control of the flow - want them to consent or confirm the sign in request every time - you can do that)
If the user has a password manager set up in their browser then that'll work too
Both iOS and Android offer APIs for doing this stuff and the work well. If you skin your native and web UIs to look similar the flow from a user's PoV is not jarring at all.
You can still use refresh tokens (ultimately secured by the platform) so you don't actually have to do the interactive flow very often anyway.
Some additional reading below. Quite a lot of thinking has gone into this from the industry so it's definitely worth digesting the current best practice.
https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html
IETF current best practice: https://www.rfc-editor.org/rfc/rfc8252
Don't make Scott hate you ;) : https://www.scottbrady91.com/OAuth/Why-the-Resource-Owner-Password-Credentials-Grant-Type-is-not-Authentication-nor-Suitable-for-Modern-Applications
For client side SPA browser apps OIDC provides the implicit grant type and uses a silent refresh and IDP session monitoring mechanism to maintain the session. Check out the oidc-client-js library which implements this approach.

MVC AD Azure Refresh Token via ADAL JavaScript Ajax and KnockoutJs

There is an inherent design flaw in the type of MVC application I have built and I believe I'm not the first to realize.
I have an MVC 4 Application that utilises AD Azure Authentication that was introduced to the application in the following way
Developing ASP.NET Apps with Azure Active Directory
Once as User is Authenticated and Home.cshtml loads, KnockoutJs is used to perform JavaScript AJAX POST and GET requests to read and write data.
So not exactly a Single Page App, but rather, a mix of traditional postbacks for Authentication and Serving Assets and Read/Write operations through AJAX.
During AJAX requests, the authentication token expires and AD is not able to refresh the token through JavaScript.
The following browser error is observed
XMLHttpRequest cannot load https://login.windows.net/xxx.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'xxx' is therefore not allowed access.
I have researched adal.js and the following posts but not sure if adal.js is the solution to my type of application
or how best to incorporate it to make it work with my type of application.
My understanding so far:
I am not using AngularJS.
I do not start out authenticating via JavaScript and I my authentication is not JavaScript driven to be able to benefit from adal.js.
Authentication is done server-side and the subsequent OAuth2 refresh token mechanism requires full page postbacks.
I've stumbled on various releated posts by Vittorio Bertocci but none address the particularities of this type of MVC application design.
ADAL, Windows Azure AD and Multi-Resource Refresh Tokens
WAAD doesn't refresh access token from javascript
Combining ADAL.Net and ADAL.js
AngularJS + ADAL.JS set Resource ID (Audience)
The issue with your setup is that you are using cookies for authenticating AJAX calls. Cookies aren't really well suited for that, and the limits of the approach typically emerge when you need to make calls outside of your domain and/or when the cookie expires. The fact that it is a common approach, largely as an evolutionary step due to the fact that proper SPA support for auth wasn't available for some time, does not make it a good approach.
You are free to stick with your current approach, but that will cause some pain. There is no established mechanism for triggering a session cookie renew from JS. Although that can be hacked together, we don't have samples for that - mostly because it's a hack :) the basic case seems easy enough, but as soon as you start considering all possible cases (what happens if while your app session expired, the user signed out of Azure AD and signed in with a different account?).
The most foolproof approach would be to abandon the hybrid approach. If you want to be a JS app, you can eliminate all the server-driven login do so and still retain the ability of doing server side flows (via onbehalf of grants, like https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet). You don;t even need to convert to angular if you don't want to, see https://github.com/AzureADSamples/SinglePageApp-jQuery-DotNet.
And if you want to be a postback based app, you can drop the JS part (though that sounds painful).
TL;DR: securing AJAX calls via cookies is not a clean solution and you are bound to feel some pain. Your choices are between patching the issues with ad hoc hacks, or refactor toward a more canonical approach. Sorry for the bad news :(

Browser and Webserver api authentication tokens

I am currently working on a solution that includes a multi tenant webApi which will be accessed by multiple clients, some of which i will be creating, some of which others will be creating.
Access to the api will be available via an ApiKey & Secret (enough for some resources) as well as username & password (for owner resources).
At the moment, the clients i have created (.Net MVC Web apps) have their own membership systems so what happens is the user of the client logs into the client system and the client system passes the login information to the Api to retrieve an authentication token.
The client membership system is really an unneeded abstraction. What i really want to do is have the user log directly into the api and the api pass back an authentication token that can be used from the browser as well as the .Net MVC client app.
My question is, what it the best way to achieve this. In my mind i seem to be struggling with 2 solutions.
1) Have a browser based login (ajax/AngularJS for instance) solution that calls the api to retrieve a token which then passes that token onto the MVC client where it will be stored (session variable maybe). Any future calls to the api that come from the .Net MVC client can pass the token on. This seems wrong to me though. I'm not even sure this is possible.
2) Utilise one of the OAuth flows so that the browser based login can call the API and retrieve a token, and the OAuth flow redirects to the MVC client which then stores the token for that user (again, in a session variable).
The Api was generated using the VS2013 WebApi template using Owin local accounts and is generating tokens via the ValidateClientCredentials and ValidateResourceOwnerCredentials flows, but i think i need to use one of the other OAuth flows for this scenario.
I understand that another solution would be to bypass the .Net MVC client code and create a completely browser based solution using knockout or AngluarJS but it's quite a complex system and i don't really have time to do this at the moment so i'm looking for a solution that would allow me to retrieve a token from the api that can be used from my .Net MVC client and ajax calls from the browser.
Any ideas, advice would be much appreciated.
thanks in advance. Justin
If you'd rely on Azure AD as your credentials store and authentication system, you'd be able to leverage a ready to use JS library that handles authentication, AJAX calls and session management concerns automatically: see http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/.
If you can't rely on Azure AD, the code of the library and samples mentioned above can still have value as a reference to build your own system - provided that the authenticaiton system you decide to use offers similar capabilities.
HTH
V.

How would I grant user based Yammer REST API access to an ETL tool?

I've an ETL tool that is capable of making REST API calls against the Yammer network and retrieving data for analysis. Currently, how I make Yammer REST API calls is through an App that I've created. I then generated the authentication token and then used this token in the REST API calls to get at the data.
What I'd really like to do now is to provide an app that allows me to call the REST API (using the same ETL tool) without the person installing the app to have to go through the rigmarole of generating the auth token.
I suppose one approach could be to use some JavaScript that displayed the token to the user so that they could then pass it on to us... Do you folks have any other suggestions as to how I might do this?
There isn't a recommended way to skip the OAuth authorization, but you can automate a lot of it away. I created a Python script that uses the YamPy library to acquire a token. It even fires up the browser to the correct URL for authorization. You should be able to do something similar with other languages.
Calling the impersonation endpoint is another possibility. This will get you an OAuth token for another user so you'd need to have an app is just for producing OAuth tokens. It's probably a bit trickier to build right and secure than my script. Impersonation was designed for a specific category of app which means I don't recommend it by default. Even when it is a workable option it hides the authorization from end users which can potentially be a security issue, if say you app is compromised and handing out OAuth tokens. At least if the Yammer screen is in the way it's a bit more visible to the user what is happening.