使用 Azure Active Directory B2C 设置通过 GitHub 帐户注册与登录Set up sign-up and sign-in with a GitHub account using Azure Active Directory B2C

开始之前,请使用上面的选择器选择要配置的策略类型。Before you begin, use the selector above to choose the type of policy you’re configuring. Azure AD B2C 提供了两种定义用户如何与应用程序交互的方法:通过预定义的用户流,或者通过完全可配置的自定义策略Azure AD B2C offers two methods of defining how users interact with your applications: though predefined user flows, or through fully configurable custom policies. 对于每种方法,本文中所需的步骤都不同。The steps required in this article are different for each method.

备注

此功能目前以公共预览版提供。This feature is in public preview.

备注

在 Azure Active Directory B2C 中,custom policies 主要用于解决复杂方案。In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. 大多数情况下,建议使用内置的用户流For most scenarios, we recommend that you use built-in user flows.

先决条件Prerequisites

创建 GitHub OAuth 应用程序Create a GitHub OAuth application

若要在 Azure Active Directory B2C (Azure AD B2C) 中使用 GitHub 帐户登录,需要在 GitHub 开发人员门户中创建一个应用程序。To enable sign-in with a GitHub account in Azure Active Directory B2C (Azure AD B2C), you need to create an application in GitHub Developer portal. 有关详细信息,请参阅创建 OAuth 应用For more information, see Creating an OAuth App. 如果没有 GitHub 帐户,可以在 https://www.github.com/ 上注册。If you don't already have a GitHub account, you can sign up at https://www.github.com/.

  1. 使用 GitHub 凭据登录到 GitHub 开发人员门户。Sign in to the GitHub Developer with your GitHub credentials.
  2. 选择“OAuth 应用”,然后选择“新建 OAuth 应用”。Select OAuth Apps and then select New OAuth App.
  3. 输入 应用程序名称主页 URLEnter an Application name and your Homepage URL.
  4. 在“授权回调 URL”中输入 https://your-tenant-name.b2clogin.cn/your-tenant-name.partner.onmschina.cn/oauth2/authrespEnter https://your-tenant-name.b2clogin.cn/your-tenant-name.partner.onmschina.cn/oauth2/authresp in Authorization callback URL. your-tenant-name 替换为 Azure AD B2C 租户的名称。Replace your-tenant-name with the name of your Azure AD B2C tenant. 输入租户名称时,全部使用小写字母,即使租户是使用大写字母在 Azure AD B2C 中定义的,也是如此。Use all lowercase letters when entering your tenant name even if the tenant is defined with uppercase letters in Azure AD B2C.
  5. 单击“注册应用程序”。Click Register application.
  6. 复制“客户端 ID”和“客户端密钥”的值。Copy the values of Client ID and Client Secret. 将标识提供者添加到租户时需要这两个值。You need both to add the identity provider to your tenant.

将 GitHub 配置为标识提供者Configure GitHub as an identity provider

  1. 以 Azure AD B2C 租户的全局管理员身份登录 Azure 门户Sign in to the Azure portal as the global administrator of your Azure AD B2C tenant.
  2. 请确保使用包含 Azure AD B2C 租户的目录,方法是选择顶部菜单中的“目录 + 订阅”筛选器,然后选择包含租户的目录。Make sure you're using the directory that contains your Azure AD B2C tenant by selecting the Directory + subscription filter in the top menu and choosing the directory that contains your tenant.
  3. 选择 Azure 门户左上角的“所有服务”,搜索并选择 Azure AD B2CChoose All services in the top-left corner of the Azure portal, search for and select Azure AD B2C.
  4. 选择“标识提供者”,然后选择“GitHub (预览)”。Select Identity providers, then select GitHub (Preview).
  5. 输入“名称”。Enter a Name. 例如,GitHub。For example, GitHub.
  6. 对于 客户端 ID,输入你之前创建的 GitHub 应用程序的客户端 ID。For the Client ID, enter the Client ID of the GitHub application that you created earlier.
  7. 对于 客户端密码,输入你记录的客户端密码。For the Client secret, enter the Client Secret that you recorded.
  8. 选择“保存” 。Select Save.

将 GitHub 标识提供者添加到用户流Add GitHub identity provider to a user flow

  1. 在 Azure AD B2C 租户中,选择“用户流”。In your Azure AD B2C tenant, select User flows.
  2. 单击要将 GitHub 标识提供者添加到的用户流。Click the user flow that you want to add the GitHub identity provider.
  3. 在“社交标识提供者”下,选择“GitHub”。Under the Social identity providers, select GitHub.
  4. 选择“保存” 。Select Save.
  5. 若要测试策略,请选择“运行用户流”。To test your policy, select Run user flow.
  6. 对于“应用程序”,请选择前面已注册的名为“testapp1”的 Web 应用程序。For Application, select the web application named testapp1 that you previously registered. “回复 URL”应显示为 https://jwt.msThe Reply URL should show https://jwt.ms.
  7. 单击“运行用户流”Click Run user flow

创建策略密钥Create a policy key

你需要存储前面在 Azure AD B2C 租户中记录的客户端机密。You need to store the client secret that you previously recorded in your Azure AD B2C tenant.

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 请确保使用的是包含 Azure AD B2C 租户的目录。Make sure you're using the directory that contains your Azure AD B2C tenant. 选择顶部菜单中的“目录 + 订阅”筛选器,然后选择包含租户的目录。Select the Directory + subscription filter in the top menu and choose the directory that contains your tenant.
  3. 选择 Azure 门户左上角的“所有服务”,然后搜索并选择“Azure AD B2C” 。Choose All services in the top-left corner of the Azure portal, and then search for and select Azure AD B2C.
  4. 在“概述”页上选择“标识体验框架”。On the Overview page, select Identity Experience Framework.
  5. 选择“策略密钥”,然后选择“添加”。Select Policy Keys and then select Add.
  6. 对于“选项”,请选择 ManualFor Options, choose Manual.
  7. 输入策略密钥的 名称Enter a Name for the policy key. 例如,GitHubSecretFor example, GitHubSecret. 前缀 B2C_1A_ 会自动添加到密钥名称。The prefix B2C_1A_ is added automatically to the name of your key.
  8. 在“机密”中,输入前面记录的应用程序机密。In Secret, enter your client secret that you previously recorded.
  9. 在“密钥用法”处选择 SignatureFor Key usage, select Signature.
  10. 单击 创建Click Create.

将 GitHub 配置为标识提供者Configure GitHub as an identity provider

要使用户能够使用 GitHub 帐户登录,需将该帐户定义为 Azure AD B2C 可通过终结点与之通信的声明提供程序。To enable users to sign in using a GitHub account, you need to define the account as a claims provider that Azure AD B2C can communicate with through an endpoint. 该终结点将提供一组声明,Azure AD B2C 使用这些声明来验证特定的用户是否已完成身份验证。The endpoint provides a set of claims that are used by Azure AD B2C to verify that a specific user has authenticated.

可以通过在策略的扩展文件中将 GitHub 帐户添加到 ClaimsProviders 元素,将该帐户定义为声明提供程序。You can define a GitHub account as a claims provider by adding it to the ClaimsProviders element in the extension file of your policy.

  1. 打开 TrustFrameworkExtensions.xmlOpen the TrustFrameworkExtensions.xml.

  2. 找到 ClaimsProviders 元素。Find the ClaimsProviders element. 如果该元素不存在,请在根元素下添加它。If it does not exist, add it under the root element.

  3. 如下所示添加新的 ClaimsProviderAdd a new ClaimsProvider as follows:

    <ClaimsProvider>
      <Domain>github.com</Domain>
      <DisplayName>GitHub</DisplayName>
      <TechnicalProfiles>
        <TechnicalProfile Id="GitHub-OAuth2">
          <DisplayName>GitHub</DisplayName>
          <Protocol Name="OAuth2" />
          <Metadata>
            <Item Key="ProviderName">github.com</Item>
            <Item Key="authorization_endpoint">https://github.com/login/oauth/authorize</Item>
            <Item Key="AccessTokenEndpoint">https://github.com/login/oauth/access_token</Item>
            <Item Key="ClaimsEndpoint">https://api.github.com/user</Item>
            <Item Key="HttpBinding">GET</Item>
            <Item Key="scope">read:user user:email</Item>
            <Item Key="UsePolicyInRedirectUri">0</Item>
            <Item Key="UserAgentForClaimsExchange">CPIM-Basic/{tenant}/{policy}</Item>
            <!-- Update the Client ID below to the Application ID -->
            <Item Key="client_id">Your GitHub application ID</Item>
          </Metadata>
          <CryptographicKeys>
            <Key Id="client_secret" StorageReferenceId="B2C_1A_GitHubSecret"/>
          </CryptographicKeys>
          <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
            <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
            <OutputClaim ClaimTypeReferenceId="numericUserId" PartnerClaimType="id" />
            <OutputClaim ClaimTypeReferenceId="issuerUserId" />
            <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="github.com" AlwaysUseDefaultValue="true" />
            <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" AlwaysUseDefaultValue="true" />
          </OutputClaims>
          <OutputClaimsTransformations>
            <OutputClaimsTransformation ReferenceId="CreateIssuerUserId" />
            <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
            <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
            <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
            <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
          </OutputClaimsTransformations>
          <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
        </TechnicalProfile>
      </TechnicalProfiles>
    </ClaimsProvider>
    
  4. client_id 设置为应用程序注册中的应用程序 ID。Set client_id to the application ID from the application registration.

  5. 保存文件。Save the file.

添加声明转换Add the claims transformations

GitHub 技术配置文件要求将 CreateIssuerUserId 声明转换添加到 ClaimsTransformations 列表。The GitHub technical profile requires the CreateIssuerUserId claim transformations to be added to the list of ClaimsTransformations. 如果未在文件中定义 ClaimsTransformations 元素,请按如下所示添加父 XML 元素。If you don't have a ClaimsTransformations element defined in your file, add the parent XML elements as shown below. 声明转换还需要定义一个名为 numericUserId 的新声明类型。The claims transformations also need a new claim type defined named numericUserId.

  1. 搜索 BuildingBlocks 元素。Search for the BuildingBlocks element. 如果该元素不存在,请添加该元素。If the element doesn't exist, add it.
  2. 找到 ClaimsSchema 元素。Locate the ClaimsSchema element. 如果该元素不存在,请添加该元素。If the element doesn't exist, add it.
  3. 将 numericUserId 声明添加到 ClaimsSchema 元素。Add the numericUserId claim to the ClaimsSchema element.
  4. 找到 ClaimsTransformations 元素。Locate the ClaimsTransformations element. 如果该元素不存在,请添加该元素。If the element doesn't exist, add it.
  5. 将 CreateIssuerUserId 声明转换添加到 ClaimsTransformations 元素。Add the CreateIssuerUserId claims transformations to the ClaimsTransformations element.
<BuildingBlocks>
  <ClaimsSchema>
    <ClaimType Id="numericUserId">
      <DisplayName>Numeric user Identifier</DisplayName>
      <DataType>long</DataType>
    </ClaimType>
  </ClaimsSchema>
  <ClaimsTransformations>
    <ClaimsTransformation Id="CreateIssuerUserId" TransformationMethod="ConvertNumberToStringClaim">
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="numericUserId" TransformationClaimType="inputClaim" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="issuerUserId" TransformationClaimType="outputClaim" />
      </OutputClaims>
    </ClaimsTransformation>
  </ClaimsTransformations>
</BuildingBlocks>

添加用户旅程Add a user journey

此时,标识提供者已设置,但还不能在任何登录页面中使用。At this point, the identity provider has been set up, but it's not yet available in any of the sign-in pages. 如果没有自己的自定义用户旅程,请创建现有用户旅程模板的副本;如果有,则继续下一步。If you don't have your own custom user journey, create a duplicate of an existing template user journey, otherwise continue to the next step.

  1. 打开初学者包中的 TrustFrameworkBase.xml 文件。Open the TrustFrameworkBase.xml file from the starter pack.
  2. 找到并复制包含 Id="SignUpOrSignIn"UserJourney 元素的完整内容。Find and copy the entire contents of the UserJourney element that includes Id="SignUpOrSignIn".
  3. 打开 TrustFrameworkExtensions.xml 并找到 UserJourneys 元素。Open the TrustFrameworkExtensions.xml and find the UserJourneys element. 如果该元素不存在,请添加一个。If the element doesn't exist, add one.
  4. 将复制的 UserJourney 元素的完整内容粘贴为 UserJourneys 元素的子级。Paste the entire content of the UserJourney element that you copied as a child of the UserJourneys element.
  5. 对用户旅程的 ID 进行重命名。Rename the Id of the user journey. 例如,Id="CustomSignUpSignIn"For example, Id="CustomSignUpSignIn".

将标识提供者添加到用户旅程Add the identity provider to a user journey

拥有用户旅程后,将新标识提供者添加到用户旅程。Now that you have a user journey, add the new identity provider to the user journey. 首先添加登录按钮,然后将按钮链接到操作。You first add a sign-in button, then link the button to an action. 该操作是前面创建的技术配置文件。The action is the technical profile you created earlier.

  1. 在用户旅程中,查找包含 Type="CombinedSignInAndSignUp"Type="ClaimsProviderSelection" 的业务流程步骤元素。Find the orchestration step element that includes Type="CombinedSignInAndSignUp", or Type="ClaimsProviderSelection" in the user journey. 这通常是第一个业务流程步骤。It's usually the first orchestration step. ClaimsProviderSelections 元素包含用户可以用来登录的标识提供者列表。The ClaimsProviderSelections element contains a list of identity providers that a user can sign in with. 元素的顺序控制向用户呈现的登录按钮顺序。The order of the elements controls the order of the sign-in buttons presented to the user. 添加 ClaimsProviderSelection XML 元素。Add a ClaimsProviderSelection XML element. 将 TargetClaimsExchangeId 的值设置为易记名称。Set the value of TargetClaimsExchangeId to a friendly name.

  2. 在下一个业务流程步骤中,添加 ClaimsExchange 元素。In the next orchestration step, add a ClaimsExchange element. 将 ID 设置为 TargetClaimsExchangeId 的值。将 TechnicalProfileReferenceId 的值更新为先前创建的技术配置文件的 ID 。Set the Id to the value of the target claims exchange Id. Update the value of TechnicalProfileReferenceId to the Id of the technical profile you created earlier.

下面的 XML 显示使用标识提供者的用户旅程的前两个业务流程步骤:The following XML demonstrates the first two orchestration steps of a user journey with the identity provider:

<OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
  <ClaimsProviderSelections>
    ...
    <ClaimsProviderSelection TargetClaimsExchangeId="GitHubExchange" />
  </ClaimsProviderSelections>
  ...
</OrchestrationStep>

<OrchestrationStep Order="2" Type="ClaimsExchange">
  ...
  <ClaimsExchanges>
    <ClaimsExchange Id="GitHubExchange" TechnicalProfileReferenceId="GitHub-OAuth2" />
  </ClaimsExchanges>
</OrchestrationStep>

配置信赖方策略Configure the relying party policy

信赖方策略(例如 SignUpSignIn.xml)指定 Azure AD B2C 将执行的用户旅程。The relying party policy, for example SignUpSignIn.xml, specifies the user journey which Azure AD B2C will execute. 信赖方内查找 DefaultUserJourney 元素。Find the DefaultUserJourney element within relying party. 更新 ReferenceId,使其与已在其中添加标识提供者的用户旅程 ID 匹配。Update the ReferenceId to match the user journey ID, in which you added the identity provider.

在以下示例中,对于 CustomSignUpOrSignIn 用户旅程,将 ReferenceId 设置为 CustomSignUpOrSignInIn the following example, for the CustomSignUpOrSignIn user journey, the ReferenceId is set to CustomSignUpOrSignIn:

<RelyingParty>
  <DefaultUserJourney ReferenceId="CustomSignUpSignIn" />
  ...
</RelyingParty>

上传自定义策略Upload the custom policy

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 在门户工具栏中选择“目录 + 订阅”图标,然后选择包含 Azure AD B2C 租户的目录。Select the Directory + Subscription icon in the portal toolbar, and then select the directory that contains your Azure AD B2C tenant.
  3. 在 Azure 门户中,搜索并选择“Azure AD B2C”。In the Azure portal, search for and select Azure AD B2C.
  4. 在“策略”下,选择“Identity Experience Framework”。 Under Policies, select Identity Experience Framework.
  5. 选择“上传自定义策略”,然后上传已更改的两个策略文件,其顺序为:先上传扩展策略(例如 TrustFrameworkExtensions.xml),然后上传信赖方策略(例如 SignUpSignIn.xml)。Select Upload Custom Policy, and then upload the two policy files that you changed, in the following order: the extension policy, for example TrustFrameworkExtensions.xml, then the relying party policy, such as SignUpSignIn.xml.

测试自定义策略Test your custom policy

  1. 选择信赖方策略,例如 B2C_1A_signup_signinSelect your relying party policy, for example B2C_1A_signup_signin.
  2. 对于“应用程序”,选择之前注册的 Web 应用程序。For Application, select a web application that you previously registered. “回复 URL”应显示为 https://jwt.msThe Reply URL should show https://jwt.ms.
  3. 选择“立即运行”按钮。Select the Run now button.

如果登录过程成功,则浏览器会重定向到 https://jwt.ms,后者显示 Azure AD B2C 返回的令牌内容。If the sign-in process is successful, your browser is redirected to https://jwt.ms, which displays the contents of the token returned by Azure AD B2C.