Azure AD B2C:使用 iOS 应用程序登录Azure AD B2C: Sign-in using an iOS application

Microsoft 标识平台使用开放式标准,例如 OAuth2 和 OpenID Connect。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. 我们提供了本演练和其他类似文档来帮助开发人员编写可以连接到 Microsoft 标识平台的应用程序。We've provided this walkthrough and others like it to aid developers with writing applications that connect to the Microsoft Identity platform. 大部分实现 RFC6749 OAuth2 规范的库都可连接到 Microsoft 标识平台。Most libraries that implement the RFC6749 OAuth2 spec are able to connect to the Microsoft Identity platform.


Microsoft 不提供第三方库的修复程序,且尚未审查这些库。Microsoft does not provide fixes for third-party libraries and has not done a review of those libraries. 本示例使用名为 AppAuth 的第三方库,该库经测试可与 Azure AD B2C 的基本方案兼容。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.

对于 OAuth2 或 OpenID Connect 的新手,该示例配置中的大部分内容可能较难理解。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.

获取 Azure AD B2C 目录Get an Azure AD B2C directory

只有在创建目录或租户之后,才可使用 Azure AD B2C。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. 如果没有容器,请先 创建 B2C 目录 ,再继续。If you don't have one already, create a B2C directory before you continue.

创建应用程序Create an application

接下来,将应用程序注册到 Azure AD B2C 租户。Next, register an application in your Azure AD B2C tenant. 这为 Azure AD 提供了与应用安全通信所需的信息。This gives Azure AD the information it needs to communicate securely with your app.

要在 Azure AD B2C 租户中注册应用程序,可以使用新的统一“应用注册”体验或旧版“应用程序(旧版)”体验 。To register an application in your Azure AD B2C tenant, you can use our new unified App registrations experience or our legacy Applications (Legacy) experience. 详细了解此新体验Learn more about the new experience.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 在顶部菜单中选择“目录 + 订阅”筛选器,然后选择包含Azure AD B2C 租户的目录。Select the Directory + subscription filter in the top menu, and then select the directory that contains your Azure AD B2C tenant.
  3. 在左侧菜单中,选择“Azure AD B2C”。In the left menu, select Azure AD B2C. 或者,选择“所有服务”并搜索并选择“Azure AD B2C”。Or, select All services and search for and select Azure AD B2C.
  4. 选择“应用注册”,然后选择“新建注册” 。Select App registrations, and then select New registration.
  5. 输入应用程序的“名称”。Enter a Name for the application. 例如,“nativeapp1”。For example, nativeapp1.
  6. 在“支持的帐户类型”下,选择“任何组织目录中或任何标识提供者中的帐户” 。Under Supported account types, select Accounts in any organizational directory or any identity provider.
  7. 在“重定向 URI”下,使用下拉选择“公共客户端/本机(移动和桌面)” 。Under Redirect URI, use the drop-down to select Public client/native (mobile & desktop).
  8. 输入使用唯一方案的重定向 URI。Enter a redirect URI with a unique scheme. 例如,com.onmicrosoft.contosob2c.exampleapp://oauth/redirectFor example, com.onmicrosoft.contosob2c.exampleapp://oauth/redirect. 选择重定向 URI 时,有以下重要的注意事项:There are important considerations when choosing a redirect URI:
    • 开发:对于开发用途,可将重定向 URI 设置为 http://localhost,Azure AD B2C 将遵循请求中的任何端口。Development For development use, you can set the redirect URI to http://localhost and Azure AD B2C will respect any port in the request. 如果注册的 URI 包含端口,Azure AD B2C 将仅使用该端口。If the registered URI contains a port, Azure AD B2C will use that port only. 例如,如果注册的重定向 URI 为 http://localhost,则请求中的重定向 URI 可为 http://localhost:<randomport>For example, if the registered redirect URI is http://localhost, the redirect URI in the request can be http://localhost:<randomport>. 如果注册的重定向 URI 为 http://localhost:8080,则请求中的重定向 URI 必须为 http://localhost:8080If the registered redirect URI is http://localhost:8080, the redirect URI in the request must be http://localhost:8080.
    • 唯一:每个应用程序的重定向 URI 的方案必须是唯一的。Unique: The scheme of the redirect URI must be unique for every application. 在示例 com.onmicrosoft.contosob2c.exampleapp://oauth/redirect 中,com.onmicrosoft.contosob2c.exampleapp 为方案。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.
    • 完整:重定向 URI 必须同时包含方案和路径。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. 例如,//oauth/ 有效而 //oauth 失败。For example, //oauth/ works while //oauth fails. 请勿在 URI 中包含特殊字符(例如,下划线)。Don't include special characters in the URI, for example, underscores.
  9. 在“权限”下,选择“授予对 openid 和 office_access 权限的管理员许可”复选框。Under Permissions, select the Grant admin consent to openid and offline_access permissions check box.
  10. 选择“注册”。Select Register.

记录“应用程序(客户端) ID”,以便在后续步骤中使用 。Record the Application (client) ID for use in a later step.

还记录自定义重定向 URI,以便在后续步骤中使用。Also record your custom redirect URI for use in a later step. 例如,com.onmicrosoft.contosob2c.exampleapp://oauth/redirectFor example, com.onmicrosoft.contosob2c.exampleapp://oauth/redirect.

创建用户流Create your user flows

在 Azure AD B2C 中,每个用户体验由用户流定义。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.
  • 在“应用程序声明” 下,选择“显示名称” 和“用户的对象 ID” 声明。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. 保存用户流时,用户流名称带有前缀 b2c_1_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

我们在 GitHub 上提供了有关将 AppAuth 与 Azure AD B2C 配合使用的实践示例。We have provided a working sample that uses AppAuth with Azure AD B2C on GitHub. 可以下载该代码并运行它。You can download the code and run it. 若要使用自己的 Azure AD B2C 租户,请遵循 中的说明。To use your own Azure AD B2C tenant, follow the instructions in the

此示例是在 GitHub 上的 iOS AppAuth 项目中根据 README 说明创建的。This sample was created by following the README instructions by the iOS AppAuth project on GitHub. 有关示例和库的工作原理的详细信息,请参阅在 GitHub 上的 AppAuth README。For more details on how the sample and the library work, reference the AppAuth README on GitHub.

修改应用,以便将 AppAuth 与 Azure AD B2C 配合使用Modifying your app to use Azure AD B2C with AppAuth


AppAuth 支持 iOS 7 和更高版本。AppAuth supports iOS 7 and above.


可以通过指定授权终结点和令牌终结点 URI,来配置与 Azure AD B2C 的通信。You can configure communication with Azure AD B2C by specifying both the authorization endpoint and token endpoint URIs. 若要生成这些 URI,需要提供以下信息:To generate these URIs, you need the following information:

  • 租户 ID(例如, ID (for example,
  • 用户流名称(例如 B2C_1_SignUpIn)User flow name (for example, B2C_1_SignUpIn)

可以通过替换以下 URL 中的 Tenant_ID 和 Policy_Name 来生成令牌终结点 URI: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><Tenant_ID>/<Policy_Name>/oauth2/v2.0/token";

可以通过替换以下 URL 中的 Tenant_ID 和 Policy_Name 来生成授权终结点 URI: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><Tenant_ID>/<Policy_Name>/oauth2/v2.0/authorize";

运行以下代码创建 AuthorizationServiceConfiguration 对象: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...


配置或检索授权服务配置后,可以构造授权请求。After configuring or retrieving an authorization service configuration, an authorization request can be constructed. 若要创建该请求,需要提供以下信息:To create the request, you need the following information:

  • 之前记录的客户端 ID(应用程序 ID)。Client ID (APPLICATION ID) that you recorded earlier. 例如,00000000-0000-0000-0000-000000000000For example, 00000000-0000-0000-0000-000000000000.
  • 之前记录的自定义重定向 URI。Custom Redirect URI that you recorded earlier. 例如,com.onmicrosoft.contosob2c.exampleapp://oauth/redirectFor 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
                                                    scopes:@[OIDScopeOpenID, OIDScopeProfile]
                                               redirectURL:[NSURL URLWithString:kRedirectUri]

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.currentAuthorizationFlow =
    [OIDAuthState authStateByPresentingAuthorizationRequest:request
                                                   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];

要将应用程序设置为处理重定向到使用自定义方案的 URI,需要在 Info.pList 中更新“URL 方案”列表: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:

  • 打开 Info.pList。Open Info.pList.
  • 将鼠标悬停在带有“BBundle OS 类型代码”字样的行上,然后单击 + 符号。Hover over a row like 'Bundle OS Type Code' and click the + symbol.
  • 将新行重命名为“URL 类型”。Rename the new row 'URL types'.
  • 单击“URL 类型”左侧的箭头打开该树。Click the arrow to the left of 'URL types' to open the tree.
  • 单击“项目 0”左侧的箭头打开该树。Click the arrow to the left of 'Item 0' to open the tree.
  • 将项目 0 下面的第一项重命名为“URL 方案”。Rename first item underneath Item 0 to 'URL Schemes'.
  • 单击“URL 方案”左侧的箭头打开该树。Click the arrow to the left of 'URL Schemes' to open the tree.
  • 在“值”列中,“URL 方案”下面“项目 0”左侧具有空白字段。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. 创建 OIDAuthorizationRequest 对象时,该值必须与 redirectURL 中使用的方案匹配。The value must match the scheme used in redirectURL when creating the OIDAuthorizationRequest object. 本示例使用了方案“com.onmicrosoft.fabrikamb2c.exampleapp”。In the sample, the scheme 'com.onmicrosoft.fabrikamb2c.exampleapp' is used.

有关如何完成余下的过程,请参阅 AppAuth 指南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. 遵循 中的步骤输入自己的 Azure AD B2C 配置。Follow the steps in the 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. 对于功能请求,请将其添加到 UserVoiceFor feature requests, add them to UserVoice.