Authenticating Users with Azure Active Directory B2C

Integrating consumer identity management into an application

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this


0/250

last updated: 2016-08

Azure Active Directory B2C is a cloud identity management solution for consumer-facing web and mobile applications. This article demonstrates how to use Microsoft Authentication Library and Azure Active Directory B2C to integrate consumer identity management into a mobile application.

The Microsoft Authentication Library is still in preview, and should not be used in production. There may be breaking changes to this API before the final release.

Overview

Azure Active Directory B2C is an identity management service for consumer-facing applications, that allows consumers to sign-in to your application by:

  • Using their existing social accounts (Microsoft, Google, Facebook, Amazon, LinkedIn).
  • Creating new credentials (email address and password, or username and password). These credentials are referred to as local accounts.

The process for integrating the Azure Active Directory B2C identity management service into a mobile application is as follows:

  1. Create an Azure Active Directory B2C tenant. For more information, see Create an Azure AD B2C tenant on the Azure documentation center.
  2. Register your mobile application with the Azure Active Directory B2C tenant. The registration process assigns an Application ID that uniquely identifies your application, and a Redirect URL that can be used to direct responses back to your application. For more information, see Register your application on the Azure documentation center.
  3. Create a sign-up and sign-in policy. This policy will define the experiences that consumers will go through during sign-up and sign-in, and also specifies the contents of tokens the application will receive on successful sign-up or sign-in. For more information, see Extensible policy framework on the Azure documentation center.
  4. Use the Microsoft Authentication Library (MSAL) in your mobile application to initiate an authentication workflow with your Azure Active Directory B2C tenant.

As well as integrating Azure Active Directory B2C identity management into mobile applications, MSAL can also be used to integrate Azure Active Directory identity management into mobile applications. This can be accomplished by registering a mobile application with Azure Active Directory at the Application Registration Portal. The registration process assigns an Application ID that uniquely identifies your application, which should be specified when using MSAL. For more information, see How to register an app with the v2.0 endpoint on the Azure documentation center, and Authenticate Your Mobile Apps Using Microsoft Authentication Library on the Xamarin blog.

Each request that is sent to an Azure Active Directory B2C tenant specifies a policy. Policies describe consumer identity experiences such as sign-up, or sign-in. For example, a sign-up policy allows the behavior of the Azure Active Directory B2C tenant to be configured through the following settings:

  • Account types that consumers can use to sign-in to the application.
  • Data to be collected from the consumer during sign-up.
  • Multi-factor authentication.
  • Sign-up page content.
  • Token claims that the mobile application receives when the policy has executed.

An Azure Active Directory tenant can contain multiple policies of different types, which can then be used in your application as required. In addition, policies can be reused across applications, allowing you to define and modify consumer identity experiences without changing your code. For more information about policies, see Extensible Policy Framework on the Azure documentation center.

Setup

The Microsoft Authentication Library (MSAL) NuGet library must be added to the Portable Class Library (PCL) project and platform-specific projects in a Xamarin.Forms solution. The following sections provide additional setup instructions for using MSAL to communicate with an Azure Active Directory B2C tenant from a mobile application.

Portable Class Library

MSAL doesn't support Windows Phone 8.1, and so PCLs that consume MSAL will need to remove this target. This can be accomplished by retargeting PCLs to use Profile7. For more information about PCLs, see Introduction to Portable Class Libraries.

iOS

On the iOS platform, the AppDelegate class must be modified to initialize a PlatformParameters instance, as demonstrated in the following code example:

using Microsoft.Identity.Client;

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
  public override bool FinishedLaunching(UIApplication app, NSDictionary options)
  {
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());

    var result = base.FinishedLaunching(app, options);
    App.AuthenticationClient.PlatformParameters = new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController);
    return result;
  }
}

The PlatformParameters instance is used by MSAL to recognize the platform on which it's running in order to select the platform-specific authentication user experience and token storage mechanism.

Android

On the Android platform, the MainActivity class must be modified to initialize a PlatformParameters instance, as demonstrated in the following code example:

using Microsoft.Identity.Client;

[Activity(Label = "ADB2CAuthorization.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
  protected override void OnCreate(Bundle bundle)
  {
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(bundle);

    global::Xamarin.Forms.Forms.Init(this, bundle);
    LoadApplication(new App());
    App.AuthenticationClient.PlatformParameters =
      new PlatformParameters(Xamarin.Forms.Forms.Context as Activity);
  }

  protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
  {
    base.OnActivityResult(requestCode, resultCode, data);
    AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(
      requestCode, resultCode, data);
  }
}

The PlatformParameters instance is used by MSAL to recognize the platform on which it's running in order to select the platform-specific authentication user experience and token storage mechanism.

In addition, the OnActivityResult method must be overridden to ensure that control returns to MSAL once the interactive portion of the authentication workflow has ended.

Universal Windows Platform

On the Universal Windows Platform, no additional setup is required to use MSAL.

Initialization

The Microsoft Authentication Library uses members of the PublicClientApplication class to initiate an authentication workflow. The sample application declares and initializes a public property of this type in the App class named AuthenticationClient. The following code example shows how this property is initialized:

AuthenticationClient = new PublicClientApplication(Constants.ApplicationID);

When the mobile application was registered with the Azure Active Directory B2C tenant, the registration process assigned an Application ID. This ID must be specified in the PublicClientApplication constructor.

Signing In

The sign-in screen in the sample application is shown in the following screenshots:

Sign-in with social identity providers, or with a local account, are permitted. While Microsoft, Google, and Facebook, as shown above, are used as social identity providers, other identity providers can also be used.

The following code example shows how the sign-in process is invoked:

using Microsoft.Identity.Client;

async void OnLoginButtonClicked(object sender, EventArgs e)
{
  try
  {
    var result = await App.AuthenticationClient.AcquireTokenAsync(
      Constants.Scopes,
      string.Empty,
      UiOptions.SelectAccount,
      string.Empty,
      null,
      Constants.Authority,
      Constants.SignUpSignInPolicy);
    await Navigation.PushAsync(new LogoutPage(result));
  }
  catch (MsalException ex)
  {
    if (ex.Message != null && ex.Message.Contains("AADB2C90118"))
    {
      await OnForgotPassword();
    }
    if (ex.ErrorCode != "authentication_canceled")
    {
      await DisplayAlert("An error has occurred", "Exception message: " + ex.Message, "Dismiss");
    }
  }
}

The AcquireTokenAsync method presents the user with a webview that displays the authentication options defined in the Azure Active Directory B2C policy that's specified by the Constants.SignUpSignInPolicy constant. This policy defines the experiences that consumers will go through during sign-up and sign-in, and the contents of tokens the application will receive on successful sign-up or sign-in.

The result of the AcquireTokenAsync method call is an AuthenticationResult instance. If authentication is successful, the AuthenticationResult instance will contain the authentication token, which will be cached locally, and other data such as an expiration time, and user data. If authentication is unsuccessful, the AuthenticationResult instance will contain data that indicates why authentication failed. Authentication failure can occur because the user has indicated that they've forgotten their password. In this scenario the OnForgotPassword method will be invoked.

In the sample application, if authentication is successful, the current page is navigated away from. If the attempt to obtain a token is unsuccessful, the OnForgotPassword method is invoked if the user indicated that they have forgotten their password, or an error message is displayed.

Silent Re-authentication

When the first page in the application appears, an attempt is made to retrieve a user token without showing any authentication user interface. This is achieved with the AcquireTokenSilentAsync method, as demonstrated in the following code example:

protected override async void OnAppearing()
{
  try
  {
    // Look for existing user
    var result = await App.AuthenticationClient.AcquireTokenSilentAsync(Constants.Scopes);
    await Navigation.PushAsync(new LogoutPage(result));
  }
  catch
  {
    // Do nothing - the user isn't logged in
  }
  base.OnAppearing();
}

The AcquireTokenSilentAsync method attempts to retrieve a user token from the cache, without requiring the user to sign-in. This handles the scenario where a suitable token may already be present in the cache from previous sessions. If the attempt to obtain a token is successful, the current page is navigated away from. If the attempt to obtain a token is unsuccessful, nothing happens and the user will have the choice to initiate a new authentication workflow.

Signing Out

The following code example shows how the sign-out process is invoked:

App.AuthenticationClient.UserTokenCache.Clear(Constants.ClientID);

This clears all the authentication tokens from the local cache.

Resetting a Password

A password reset policy can be defined in the Azure Active Directory B2C tenant that applies to local accounts. This policy describes the experience that consumers will experience during password reset, and the token claims that the application will receive on successful password reset. When the user indicates that they've forgotten their password, the OnForgotPassword method will be invoked, which is shown in the following code example:

async Task OnForgotPassword()
{
  try
  {
    await App.AuthenticationClient.AcquireTokenAsync(
      Constants.Scopes,
      string.Empty,
      UiOptions.SelectAccount,
      string.Empty,
      null,
      Constants.Authority,
      Constants.ResetPasswordPolicy);
  }
  catch (MsalException)
  {
    // Do nothing - ErrorCode will be displayed in OnLoginButtonClicked
  }
}

This overload of the AcquireTokenAsync method specifies the name of the password reset policy that's defined in the Azure Active Directory B2C tenant, and invokes the workflow defined in that policy.

Summary

This article demonstrated how to use Microsoft Authentication Library (MSAL) and Azure Active Directory B2C to integrate consumer identity management into a mobile application. Azure Active Directory B2C is a cloud identity management solution for consumer-facing web and mobile applications.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.