App Service Auth and Azure AD B2C (Part 2)

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:

<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>

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:

App.MobileClient.LoginAsync(
  MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
  new Dictionary<string, string>
  {
    { "p", "B2C_1_SignInWithMFA" }
  }

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.

Generating an App Key in the B2C Management Portal
Generating an App Key in the B2C Management Portal

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.

Setting the B2C app key as the Easy Auth client secret.
Setting the B2C app key as the Easy Auth client secret.

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

<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>

Updated Mobile App SDK C# Example

App.MobileClient.LoginAsync(
  MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
  new Dictionary<string, string>
  {
    { "p", "B2C_1_SignInWithMFA" },
    { "scope", "openid+offline_access" }
  }

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.

Starting page when unauthenticated
Demo app starting page when unauthenticated

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.

Phone authentication
Phone authentication when using Azure AD B2C

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.

Policy Actions
This B2C demo app supports updating the user profile and resetting the password used for logging in.
B2C Claims
This B2C policy is configured to return the object ID, postal code, name and email address.

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.

App Service Auth and Azure AD Domain Hints

When creating web, mobile, API, or Function apps for use by members of your organization, it’s often the case that you’re using Azure Active Directory and you want to remove the option to log in with non-organizational credentials. For example, you want to prevent users from accidentally logging in with MSA credentials (hotmail.com, live.com, outlook.com, etc.). This can be done by leveraging what’s known as a domain hint when navigating users to the Azure AD login page.

Domain hints will do two things for you: 1) remove the home realm discovery page from the login flow and 2) ensure that users can’t accidentally auto-log into your app using wrong credential types (for example, MSA credentials). More background information on Azure AD’s support for domain hints can be found on the Microsoft Enterprise Mobility blog:

https://blogs.technet.microsoft.com/enterprisemobility/2015/02/11/using-azure-ad-to-land-users-on-their-custom-login-page-from-within-your-app/

Vittorio Bertocci also talks about domain hints in his post on Skipping the Home Realm Discovery Page in Azure AD., demonstrating how to use them when using ADAL and the OpenID Connect Middleware to build your web app. In this post, however, I’ll describe how enable domain hints when using App Service’s integrated Easy Auth feature.

Default Login Parameters

Most web apps will want to configure domain hints to be used for all logins. Unfortunately you cannot configure default domain hints in this way using the Azure portal today. Instead, you must use the App Service Management API. Until we get around to building a portal experience, I recommend that most people configure default domain hints in Azure Resource Explorer. This can be done using the following steps:

  1. Search for your web, mobile or API app using the search bar. Alternatively, you can navigate directly to your app if you click on the Resource Explorer link in the tools section of the portal.
  2. Under your site node, navigate to /config/authsettings.
  3. Click Edit to enable making changes.
  4. Set additionalLoginParams to the following (This is a JSON array value): ["domain_hint=microsoft.com"]
  5. Click the Read/Write button at the top of the page to enable making changes.
  6. Click the PUT button to save your changes.

The JSON configuration for your auth settings should look something like the screenshot below. In my case, I specified domain_hint=microsoft.com since the app shown here is intended to be used by Microsoft employees.

DomainHints_ResourceExplorer

Once this is done, users will no longer see the home realm discovery page when logging into the app. Instead, users will be immediately directed to the organizational login page, ensuring they cannot intentionally or accidentally log in with the wrong credentials.

Using the Login API

If you’re building an app that invokes the built-in /.auth/login/aad REST API, you can alternatively specify domain_hint={domain} as a query string parameter to get the same effect.

For example, if I’m writing a mobile client and using the App Service .NET SDK, I could write the following code to initiate a login using a domain hint for contoso.com.

var user = App.MobileClient.LoginAsync(
  MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
  new Dictionary<string, string>
  {
    { "domain_hint", "contoso.com" }
  }

Similarly, I could create a login link in a web page using HTML that includes a domain_hint parameter.

<a href="/.auth/login/aad?domain_hint=contoso.com">Login</a>

This allows me to specify login hints without changing the auth settings of the app as I showed in the first part of this post. In theory, this would also allow me to create multiple login links, one for each domain that my Azure AD application supports. Note that if an app is already configured with a default domain hint, the query string parameter will override that default.

Conclusion

In conclusion, most single-tenant applications will want to use domain hints to optimize the login experience. These hints allows you to skip the home realm discovery page in the Azure AD login sequence and mitigates the common problem where the browser will try to log into the app using MSA credentials via SSO. Depending on the type of application you are building, you can use either the default login parameter method or you can explicitly specify login hints via the built-in /.auth/login/aad endpoint.

App Service Auth and Azure AD B2C

An exciting new preview feature which was recently added to Azure Active Directory is Azure Active Directory B2C. “B2C” stands for “Business to Consumer” and allows a developer to add user and login management to their application with very little (if any) coding. This also includes login integration with social identity providers like Facebook, Amazon, LinkedIn, etc. Check out their documentation and blog posts for more details. My colleague Swaroop from the Azure AD team also has a nice //build video where you can see it in action.

From my perspective, App Service Authentication / Authorization (Easy Auth) shares a similar goal of B2C, which is to make it really easy to build identity into your application. We saw a great opportunity to make these features work well together, giving you both an identity management system as well as login and OAuth token management without requiring a single line of code.

In this post, I’ll describe how you can use Easy Auth to add Azure AD B2C capabilities to your App Service Web App.

Creating an App Service Web App

Hopefully you know how to do this by now. Go ahead and create a web app (or an API/mobile/function app – they all work the same way) and make a note of the URL. For example, when drafting this blog post and walking through the steps, I created https://cgillum-b2c-preview.azurewebsites.net. Use your own web app URL in place of mine wherever you see it in these instructions. However, don’t configure Authentication / Authorization yet. We’ll do that in a later step.

Creating the Azure AD B2C Tenant and Application

We don’t currently support an “Express” setup of B2C like we do for classic Azure AD, so these steps will need to be done manually. You can find detailed instructions for this below:

  1. Create an Azure AD B2C tenant
  2. Register your application

Note that in step 2, you’ll need to use the https address of the web app you previously created as the Reply URL and you must suffix it with “/.auth/login/aad/callback” (again, in my case this is https://cgillum-b2c-preview.azurewebsites.net/.auth/login/aad/callback). Once this is done, you should have an application in the B2C portal which looks something like the following:

B2C Application Blade

Make a note of the Application Client ID that you see in the Application blade. You’ll need this in a later step.

Adding a Sign-Up/Sign-In Policy

For simplicity, we’ll create a single B2C “policy” which allows the user to sign in or sign up if they don’t already have an account. In the portal, this is the Sign-up or sign-in policies selection. Add a new policy (assuming you don’t have one already). The details of the policy don’t matter too much, so I won’t provide any specific guidance here. There are a lot of options, including whether to configure social identity providers. In my case, I set up email login as well as Google and Facebook. To get started quickly, I suggest you use the email sign-up policy. When you’re done, make a note of the Metadata Endpoint for this policy URL which gets generated, like in the screenshot below:

B2C Policy Blade

Azure AD B2C supports other policy types as well, but the combination sign-up/sign-in is currently the one best suited for Easy Auth login integration.

Configure Easy Auth

Now let’s go back to the web app we previously created. We’ll configure Easy Auth with Azure AD using the Advanced configuration option. The steps are:

  1. In the portal in the context of your web app, click the Settings icon.
  2. Set App Service Authentication to On
  3. Configure Azure Active Directory
  4. Select the Advanced management mode
  5. Set the Client ID to be the Application Client ID from before.
  6. Set the Issuer URL to be the Metadata Endpoint for this policy URL value that was generated from your sign-in/sign-on B2C policy.
  7. Click OK and then the Save icon to save your changes.

Your Authentication / Authorization settings blade should look something like the following:

Authentication / Authorization Blade

Now if you navigate to your site, you should see the B2C login page that you configured previously. Depending on how it was configured, you can sign up using social identity credentials or you can sign up using username (or email) and password. You will also be prompted for additional registration information, such as your name, etc (again, all dictated by the policies you configured).

Here is an example of what your initial sign-in page might look like. Notice the link on the bottom of the image which allows users to register:

B2C Login Page

Below is an example of what your “sign-up” registration page will look like. If you selected the email option, Azure AD B2C will even implement the email verification workflow for you.

B2C Sign-Up Page

That’s it! You’ve now created a skeleton B2C web application that allows users to sign-up and sign-in without writing any code or deploying any databases! I’ve used all the defaults in terms of styling, but Azure AD B2C does allow you to customize the look and feel of these pages to match your own application branding, if you choose. See the B2C UI customization documentation for more information.

Once signed in, you can write code which inspects the inbound HTTP headers and/or the /.auth/me endpoint (both described in my earlier Token Store post) to get more information about the user. If you’re running an ASP.NET application, you can also enumerate the claims on the current ClaimsPrincipal. Specifically, you should be able to see all the claims that you configured in your B2C policy. This is great because you don’t need to provision your own database which contains this information – it’s built into the B2C directory and can be accessed using the features of Easy Auth.

Azure AD B2C Social Providers vs. Easy Auth Social Providers

One thing you may have noticed is that there are now two ways to incorporate social logins into your web app: using B2C policies or configuring them directly in the Authentication / Authorization settings. Ideally, there would be just one which is common between the two technologies. Unfortunately we’re not there yet. Until then, here are some important differences between social providers in Azure AD B2C and Easy Auth:

  • Different identity providers: B2C and Easy Auth support different providers. At the time of writing, B2C supports MSA, Facebook, Google, LinkedIn, and Amazon identities. Easy Auth, however, supports MSA, Facebook, Google, and Twitter.
  • Client-Directed Login: Both B2C and Easy Auth support server-directed social logins where the login flow is controlled by the browser. However, only Easy Auth supports client-directed logins where the login flow is controlled by the client operating system (typically a mobile OS or a JavaScript client).
  • User Claims: B2C provides a somewhat normalized set of user claims for each login. These claims are similar to what you’d see in an ordinary AAD login. The claims are also configurable. With Easy Auth, however, the claims are static and in many cases are different for each identity provider.
  • OAuth Tokens: With Easy Auth, the application code has direct access to the provider-specific OAuth tokens. This is useful if you want to make graph API calls on behalf of the logged-in user (for example, calling the Facebook Graph to post a photo to the user’s timeline). B2C, however, does not expose the provider OAuth tokens to your application code.

If social identity integration is important to your app, then consider these differences very carefully when deciding between the two options. Note that these limitations will certainly change as both Easy Auth and Azure AD B2C evolve over time, hopefully in a way that better aligns them together (this is certainly our goal, internally).

Taking it to the Next Level

This post demonstrated using a single, global B2C policy within a web app in a way that doesn’t require any code or database setup. If you are a mobile, API, or SPA app developer, I have written a followup post which goes into more details about how to use code to dynamically select B2C policies, how to set up token refresh, and even included a sample SPA app which demonstrates these capabilities. Check it out in Part 2 of the App Service + Azure AD B2C series.