Azure AD B2C: Sign-in using an iOS application

The Microsoft identity platform uses open standards such as OAuth2 and OpenID Connect. Using an open standard protocol offers more developer choice when selecting a library to integrate with our services. We've provided this walkthrough and others like it to aid developers with writing applications that connect to the Microsoft Identity platform. Most libraries that implement the RFC6749 OAuth2 spec are able to connect to the Microsoft Identity platform.

Warning

Microsoft does not provide fixes for third-party libraries and has not done a review of those libraries. This sample is using a third-party library called AppAuth that has been tested for compatibility in basic scenarios with the Azure AD B2C. Issues and feature requests should be directed to the library's open-source project. For more information, see this article.

If you're new to OAuth2 or OpenID Connect, much of this sample configuration may not make much sense to you. We recommend you look at a brief overview of the protocol we've documented here.

Get an Azure AD B2C directory

Before you can use Azure AD B2C, you must create a directory, or tenant. A directory is a container for all your users, apps, groups, and more. If you don't have one already, create a B2C directory before you continue.

Create an application

Next, register an application in your Azure AD B2C tenant. This gives Azure AD the information it needs to communicate securely with your app.

  1. Sign in to the Azure portal.
  2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your Azure AD B2C tenant.
  3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
  4. Select Applications, and then select Add.
  5. Enter a name for the application. For example, nativeapp1.
  6. For Native client, select Yes.
  7. Enter a Custom Redirect URI with a unique scheme. For example, com.onmicrosoft.contosob2c.exampleapp://oauth/redirect. There are two important considerations when choosing a redirect URI:
    1. Unique: The scheme of the redirect URI must be unique for every application. In the example com.onmicrosoft.contosob2c.exampleapp://oauth/redirect, com.onmicrosoft.contosob2c.exampleapp is the scheme. This pattern should be followed. If two applications share the same scheme, the user is given a choice to choose an application. If the user chooses incorrectly, the sign-in fails.
    2. Complete: The redirect URI must have a both a scheme and a path. The path must contain at least one forward slash after the domain. For example, //oauth/ works while //oauth fails. Don't include special characters in the URI, for example, underscores.
  8. Select Create.

Record the APPLICATION ID for use in a later step. Next, select the application in the list and record the Custom Redirect URI, also for use in a later step. For example, com.onmicrosoft.contosob2c.exampleapp://oauth/redirect.

Create your user flows

In Azure AD B2C, every user experience is defined by a user flow. This application contains one identity experience: a combined sign-in and sign-up. When you create the user flow, be sure to:

  • Under Sign-up attributes, select the attribute Display name. You can select other attributes as well.
  • Under Application claims, select the claims Display name and User's Object ID. You can select other claims as well.
  • Copy the Name of each user flow after you create it. Your user flow name is prefixed with b2c_1_ when you save the user flow. You need the user flow name later.

After you have created your user flows, you're ready to build your app.

Download the sample code

We have provided a working sample that uses AppAuth with Azure AD B2C on GitHub. You can download the code and run it. To use your own Azure AD B2C tenant, follow the instructions in the README.md.

This sample was created by following the README instructions by the iOS AppAuth project on GitHub. For more details on how the sample and the library work, reference the AppAuth README on GitHub.

Modifying your app to use Azure AD B2C with AppAuth

Note

AppAuth supports iOS 7 and above. However, to support social logins on Google, SFSafariViewController is needed which requires iOS 9 or higher.

Configuration

You can configure communication with Azure AD B2C by specifying both the authorization endpoint and token endpoint URIs. To generate these URIs, you need the following information:

  • Tenant ID (for example, contoso.onmicrosoft.com)
  • User flow name (for example, B2C_1_SignUpIn)

The token endpoint URI can be generated by replacing the Tenant_ID and the Policy_Name in the following URL:

static NSString *const tokenEndpoint = @"https://<Tenant_name>.b2clogin.com/te/<Tenant_ID>/<Policy_Name>/oauth2/v2.0/token";

The authorization endpoint URI can be generated by replacing the Tenant_ID and the Policy_Name in the following URL:

static NSString *const authorizationEndpoint = @"https://<Tenant_name>.b2clogin.com/te/<Tenant_ID>/<Policy_Name>/oauth2/v2.0/authorize";

Run the following code to create your AuthorizationServiceConfiguration object:

OIDServiceConfiguration *configuration =
    [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint tokenEndpoint:tokenEndpoint];
// now we are ready to perform the auth request...

Authorizing

After configuring or retrieving an authorization service configuration, an authorization request can be constructed. To create the request, you need the following information:

  • Client ID (APPLICATION ID) that you recorded earlier. For example, 00000000-0000-0000-0000-000000000000.
  • Custom Redirect URI that you recorded earlier. For example, com.onmicrosoft.contosob2c.exampleapp://oauth/redirect.

Both items should have been saved when you were registering your app.

OIDAuthorizationRequest *request =
    [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
                                                  clientId:kClientId
                                                    scopes:@[OIDScopeOpenID, OIDScopeProfile]
                                               redirectURL:[NSURL URLWithString:kRedirectUri]
                                              responseType:OIDResponseTypeCode
                                      additionalParameters:nil];

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.currentAuthorizationFlow =
    [OIDAuthState authStateByPresentingAuthorizationRequest:request
                                   presentingViewController:self
                                                   callback:^(OIDAuthState *_Nullable authState, NSError *_Nullable error) {
        if (authState) {
            NSLog(@"Got authorization tokens. Access token: %@", authState.lastTokenResponse.accessToken);
            [self setAuthState:authState];
        } else {
            NSLog(@"Authorization error: %@", [error localizedDescription]);
            [self setAuthState:nil];
        }
    }];

To set up your application to handle the redirect to the URI with the custom scheme, you need to update the list of 'URL Schemes' in your Info.pList:

  • Open Info.pList.
  • Hover over a row like 'Bundle OS Type Code' and click the + symbol.
  • Rename the new row 'URL types'.
  • Click the arrow to the left of 'URL types' to open the tree.
  • Click the arrow to the left of 'Item 0' to open the tree.
  • Rename first item underneath Item 0 to 'URL Schemes'.
  • Click the arrow to the left of 'URL Schemes' to open the tree.
  • In the 'Value' column, there is a blank field to the left of 'Item 0' underneath 'URL Schemes'. Set the value to your application's unique scheme. The value must match the scheme used in redirectURL when creating the OIDAuthorizationRequest object. In the sample, the scheme 'com.onmicrosoft.fabrikamb2c.exampleapp' is used.

Refer to the AppAuth guide on how to complete the rest of the process. If you need to quickly get started with a working app, check out the sample. Follow the steps in the README.md to enter your own Azure AD B2C configuration.

We are always open to feedback and suggestions! If you have any difficulties with this article, or have recommendations for improving this content, we would appreciate your feedback at the bottom of the page. For feature requests, add them to UserVoice.