Note: This post was cross-posted from CGillum Dev Blog.
EDIT 1/23/2017: Updated token refresh section with simplified instructions and added code snippets.
This post is a continuation of my previous post on
App Service Auth and Azure AD B2C, where I demonstrated how you can create a web app that uses Azure AD B2C without writing any code. If you haven't done so already, be sure to read that post to get proper context for this one.
In a recent service update, we've improved our overall support for B2C in Azure App Service. This includes enhancing our existing web app support, but more importantly includes adding full support for leveraging B2C in mobile, API and function apps. More specifically, support has been added for the
Easy Auth Token Refresh API. Additionally, the Login API has been updated to support specifying specific B2C policies as arguments. If you're a Mobile app developer, these improvements will make using Azure AD B2C in your mobile app
significantly easier.
This post will go into more details about these improvements, show a few code snippets, and conclude by demonstrating these B2C capabilities in a simple demo web app.
Pick Your Policy
Specific B2C policies can be invoked using the built-in Easy Auth login API for AAD. If you're not familiar with the Easy Auth login API, it works by allowing you to initiate a server-directed login by sending a GET request to your web, mobile, API, or function app's built-in
{root}/.auth/login/aad endpoint. This endpoint supports the
standard sign-in query string parameters for AAD, including the newly added
p={policy} query string parameter which allows you to specify a B2C policy by name.
For example, one could use the following HTML in a web app to create hyperlinks that invoke specific B2C policy workflows, such as editing the user profile or resetting the password:
[html]
<a href="/.auth/login/aad?p=B2C_1_EditProfile&post_login_redirect_uri=/">Edit Profile</a>
<a href="/.auth/login/aad?p=B2C_1_ResetPassword&post_login_redirect_uri=/">Reset Password</a>
[/html]
Clicking one of these links will automatically redirect the user to the corresponding B2C policy page and allow the user to edit their user profile or reset their password accordingly.
If you're writing a native client which uses one of the
App Service Mobile Client SDK flavors, you could write something similar in platform-specific code. The example below shows how a mobile client app written in C# can invoke a B2C sign-in policy that requires MFA:
[csharp]
App.MobileClient.LoginAsync(
MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
new Dictionary<string, string>
{
{ "p", "B2C_1_SignInWithMFA" }
}
[/csharp]
In this case, the user will presented with a native web view dialog which allows the end user to sign in using MFA (phone authentication, etc.). The primary thing to keep in mind about this experience is that these B2C policies can be easily invoked with just a few simple lines of client-side code. No platform-specific middleware or server-side code is required.
One important note of caution: the claims associated with the signed-in user will be updated every time you invoke a B2C policy. If your app depends on the presence of specific claims, make sure they are explicitly configured in each of your B2C policies.
Refreshing Tokens (Optional)
Easy Auth also has a built-in API for refreshing both provider-specific OAuth tokens and the app-specific authentication tokens. It works similar to the login API, in that it requires a GET request to the app's built-in
{root}/.auth/refresh endpoint. More information on token refresh (and our token management story all-up) can be found in my earlier
App Service Token Store blog post.
This token refresh support also extends to Azure AD B2C apps and is completely optional. However, leveraging token refresh is very important if you're building a native app to ensure a smooth user experience. In order to set this up, you will need to do the following:
Create an app key for your B2C application
Creating app keys can be done in the Azure management portal for B2C.
[caption id="attachment_198" align="aligncenter" width="951"]
Generating an App Key in the B2C Management Portal[/caption]
Make a note of the app key that gets auto-generated by the portal. We'll need it to configure Easy Auth in the next step.
Update the Easy Auth Settings
Easy Auth doesn't require an app key by default and instead relies on the
OpenID Connect Implicit Flow to implement secure logins. In order to get refresh tokens, however, we need to switch to the
Hybrid Flow (Don't worry if you don't understand what these mean, Easy Auth will take care of the protocol details for you).
To make this protocol switch, you need to update the App Service Auth settings for your app with the key from the previous step. This can be done in the Advanced tab in the Azure Active Directory portal.
[caption id="attachment_2865" align="alignnone" width="1190"]
Setting the B2C app key as the Easy Auth client secret.[/caption]
Now that you’ve enabled the hybrid flow, your app needs to start requesting refresh tokens from B2C. This can be done by updating the login parameters in your app code to include the
offline_access scope.
Updated HTML Example
[html]
<a href="/.auth/login/aad?p=B2C_1_EditProfile&post_login_redirect_uri=/&scope=openid+offline_access">Edit Profile</a>
<a href="/.auth/login/aad?p=B2C_1_ResetPassword&post_login_redirect_uri=/&scope=openid+offline_access">Reset Password</a>
[/html]
Updated Mobile App SDK C# Example
[csharp]
App.MobileClient.LoginAsync(
MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
new Dictionary<string, string>
{
{ "p", "B2C_1_SignInWithMFA" },
{ "scope", "openid+offline_access" }
}
[/csharp]
Once this is done, all future logins should result in refresh tokens in the app's built-in token store. You can then write client code which invokes the
{root}/.auth/refresh API (or use the corresponding Mobile Client SDK method) to periodically refresh these tokens, which allows your app to function for longer periods of time without requiring a re-auth.
Demo App
To demonstrate all of this, I've created a single-page application (aka a SPA app) written using HTML, jQuery, and Bootstrap. It's a trivial app written by someone who is clearly not a UI designer (me) and demonstrates the various patterns described in this blog post. You can browse to it
here and play around with it (I promise not to give out your information if you decide to provide it), or simply copy the source code and host it yourself in your own App Service web app. Note that I theoretically could have also built this using the
iOS,
Android,
UWP/Xamarin, or one of the other mobile SDKs that are provided, but it was simpler for me to build a plain-old HTML web app. :)
The important thing to keep in mind is that there is absolutely no auth code in this sample (in fact, no backend code at all). All of this is implemented on the client and in the App Service platform with the help of Azure AD B2C. No SDKs required.
When you first visit the demo page, you will be given two login options. One is a standard email-based login and the other is an MFA login which requires you to register a phone number for phone authentication.
[caption id="attachment_183" align="aligncenter" width="510"]
Demo app starting page when unauthenticated[/caption]
The phone authentication provided by B2C allows you to do phone calls or SMS in my case. You can enter the provided code to complete the authentication.
[caption id="attachment_182" align="aligncenter" width="419"]
Phone authentication when using Azure AD B2C[/caption]
Once signed-in, you will see a few B2C policy actions that you can invoke as well as a set of user claims displayed on the page. There's also a sign-out button which uses Easy Auth's built-in Logout API to clear the session.
[caption id="attachment_185" align="aligncenter" width="992"]
This B2C demo app supports updating the user profile and resetting the password used for logging in.[/caption]
[caption id="attachment_189" align="aligncenter" width="1003"]
This B2C policy is configured to return the object ID, postal code, name and email address.[/caption]
Note that one of the claims,
https://schemas.microsoft.com/claims/authnclassreference, contains the name of the B2C policy that the user logged-in with. Your application code can take advantage of this if, for example, you want to grant special permissions to users who log in using a higher-privilege B2C policy.
Again, it's a very simple app to quickly demonstrate some of the powerful capabilities of the App Service "Easy Auth" platform when combined with Azure AD B2C. My hope is that this is enough to give you some ideas about how you can leverage the Azure AD B2C platform in your own App Service apps.
Following Up
Have a technical questions about Azure App Service and/or Azure AD B2C? Head over to
StackOverflow.com and tag your questions with
azure-app-service and/or
azure-ad-b2c accordingly. We monitor posts with these tags and are happy to help.