在 Azure Active Directory B2C 自定义策略中定义 ID 令牌提示技术配置文件Define an ID token hint technical profile in an Azure Active Directory B2C custom policy

通过 Azure AD B2C,信赖方应用可将入站 JWT 作为 OAuth2 授权请求的一部分发送。Azure AD B2C allows relying party applications to send an inbound JWT as part of the OAuth2 authorization request. JWT 令牌可以由信赖方应用或标识提供者颁发,并且可以传递有关用户或授权请求的提示。The JWT token can be issued by a relying party application or an identity provider, and it can pass a hint about the user or the authorization request. Azure AD B2C 验证签名、颁发者名称和令牌受众,并从入站令牌中提取声明。Azure AD B2C validates the signature, issuer name, and token audience, and extracts the claim from the inbound token.

用例Use cases

可以使用此解决方案将数据发送到封装在单个 JWT 令牌中的 Azure AD B2C。You can use this solution to send data to Azure AD B2C encapsulated in a single JWT token. 通过电子邮件邀请注册的解决方案以 id_token_hint 为基础,系统管理员可以向用户发送签名邀请。The SignUp with email invitation solution, where your system admin can send a signed invite to users, is based on id_token_hint. 只有有权访问邀请电子邮件的用户才能在目录中创建帐户。Only users with access to the invite email can create the account in the directory.

令牌签名方法Token signing approach

通过 id_token_hint,令牌颁发者(信赖方应用或标识提供者)会组合令牌,然后使用签名密钥对令牌进行签名,以证明令牌来自受信任的源。With id_token_hint, the token issuer (a relying party app or an identity provider) composes the token, and then signs it by using a signing key to prove the token comes from a trusted source. 签名密钥可以是对称的,也可以是非对称的。The signing key can be symmetric or asymmetric. 对称加密(私钥加密)使用共享机密来签署和验证签名。Symmetric cryptography, or private key cryptography, uses a shared secret to both sign and validate the signature. 非对称加密(公钥加密)是使用私钥和公钥的加密系统。Asymmetric cryptography, or public key cryptography, is a cryptographic system that uses both a private key and a public key. 私钥只为令牌颁发者所知,并用于对令牌进行签名。The private key is known only to the token issuer and is used to sign the token. 公钥通过 Azure AD B2C 策略共享以验证令牌的签名。The public key is shared with the Azure AD B2C policy to validate the signature of the token.

令牌格式Token format

id_token_hint 必须是有效的 JWT 令牌。The id_token_hint must be a valid JWT token. 下表列出了必需的声明。The following table lists the claims that are mandatory. 其他声明是可选的。Additional claims are optional.

名称Name 声明Claim 示例值Example value 说明Description
读者Audience aud a489fc44-3cc0-4a78-92f6-e413cd853eae 标识令牌的目标接收方。Identifies the intended recipient of the token. 这是令牌颁发者定义的任意字符串。This is an arbitrary string defined by the token issuer. Azure AD B2C 将验证此值,如果不匹配,则拒绝该令牌。Azure AD B2C validates this value and rejects the token if it doesn't match.
颁发者Issuer iss https://localhost 标识安全令牌服务(令牌颁发者)。Identifies the security token service (token issuer). 这是令牌颁发者定义的任意 URI。This is an arbitrary URI defined by the token issuer. Azure AD B2C 将验证此值,如果不匹配,则拒绝该令牌。Azure AD B2C validates this value and rejects the token if it doesn't match.
过期时间Expiration time exp 1600087315 令牌失效的时间,以纪元时间表示。The time at which the token becomes invalid, represented in epoch time. Azure AD B2C 不会验证此声明。Azure AD B2C doesn't validate this claim.
生效时间Not before nbf 1599482515 令牌生效的时间,以纪元时间表示。The time at which the token becomes valid, represented in epoch time. 此时间通常与颁发令牌的时间相同。This time is usually the same as the time the token was issued. Azure AD B2C 不会验证此声明。Azure AD B2C doesn't validate this claim.

以下令牌是有效 ID 令牌的示例:The following token is an example of a valid ID token:

{
  "alg": "HS256",
  "typ": "JWT"
}.{
  "displayName": " John Smith",
  "userId": "john.s@contoso.com",
  "nbf": 1599482515,
  "exp": 1600087315,
  "iss": "https://localhost",
  "aud": "a489fc44-3cc0-4a78-92f6-e413cd853eae"
}

协议Protocol

“Protocol”元素的“Name”属性必须设置为 NoneThe Name attribute of the Protocol element needs to be set to None. 例如,IdTokenHint_ExtractClaims 技术配置文件的协议为 NoneFor example, the protocol for the IdTokenHint_ExtractClaims technical profile is None:

<TechnicalProfile Id="IdTokenHint_ExtractClaims">
  <DisplayName> My ID Token Hint TechnicalProfile</DisplayName>
  <Protocol Name="None" />
  ...

技术配置文件是从 GetClaims 类型的业务流程步骤中调用的。The technical profile is called from an orchestration step with type of GetClaims.

<OrchestrationStep Order="1" Type="GetClaims" CpimIssuerTechnicalProfileReferenceId="IdTokenHint_ExtractClaims" />

输出声明Output claims

OutputClaims 元素包含要从 JWT 令牌中提取的声明列表。The OutputClaims element contains a list of claims to be extracted from the JWT token. 可能需要将策略中定义的声明名称映射到 JWT 令牌中定义的名称。You may need to map the name of the claim defined in your policy to the name defined in the JWT token. 只要设置了 DefaultValue 属性,就还可以包含 JWT 令牌不会返回的声明。You can also include claims that aren't returned by the JWT token, as long as you set the DefaultValue attribute.

MetadataMetadata

使用对称密钥时,以下元数据是相关的。The following metadata is relevant when using symmetric key.

AttributeAttribute 必需Required 描述Description
颁发者issuer Yes 标识安全令牌服务(令牌颁发者)。Identifies the security token service (token issuer). 此值必须与 JWT 令牌声明中的 iss 声明相同。This value must be identical to the iss claim within the JWT token claim.
IdTokenAudienceIdTokenAudience Yes 标识令牌的目标接收方。Identifies the intended recipient of the token. 必须与 JWT 令牌声明中的 aud 声明相同。Must be identical to the aud claim withing the JWT token claim.

使用非对称密钥时,以下元数据是相关的。The following metadata is relevant when using an asymmetric key.

AttributeAttribute 必需Required 描述Description
METADATAMETADATA Yes 指向令牌颁发者配置文档的 URL,也称为 OpenID 已知配置终结点。A URL that points to a token issuer configuration document, which is also known as an OpenID well-known configuration endpoint.
颁发者issuer No 标识安全令牌服务(令牌颁发者)。Identifies the security token service (token issuer). 此值可用于覆盖元数据中配置的值,并且必须与 JWT 令牌声明中的 iss 声明相同。This value can be used to overwrite the value configured in the metadata, and must be identical to the iss claim within the JWT token claim.
IdTokenAudienceIdTokenAudience No 标识令牌的目标接收方。Identifies the intended recipient of the token. 必须与 JWT 令牌声明中的 aud 声明相同。Must be identical to the aud claim withing the JWT token claim.

加密密钥Cryptographic keys

使用对称密钥时,CryptographicKeys 元素包含以下属性:When using a symmetric key, the CryptographicKeys element contains the following attribute:

AttributeAttribute 必需Required 说明Description
client_secretclient_secret Yes 用于验证 JWT 令牌签名的加密密钥。The cryptographic key that is used to validate the JWT token signature.

操作指南How-to guide

使用对称密钥颁发令牌Issue a token with symmetric keys

步骤 1。Step 1. 创建一个共享密钥Create a shared key

创建可用于对令牌进行签名的密钥。Create a key that can be used to sign the token. 例如,使用以下 PowerShell 代码生成密钥。For example, use the following PowerShell code to generate a key.

$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()
$newClientSecret = [System.Convert]::ToBase64String($bytes)
$newClientSecret

此代码创建机密字符串(如 VK62QTn0m1hMcn0DQ3RPYDAr6yIiSvYgdRwjZtU5QhI=)。This code creates a secret string like VK62QTn0m1hMcn0DQ3RPYDAr6yIiSvYgdRwjZtU5QhI=.

步骤 2。Step 2. 将签名密钥添加到 Azure AD B2CAdd the signing key to Azure AD B2C

令牌颁发者使用的同一密钥需要在 Azure AD B2C 策略密钥中创建。The same key that is used by the token issuer needs to be created in your Azure AD B2C policy keys.

  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” 。On the overview page, under Policies , select Identity Experience Framework .
  5. 选择“策略密钥”Select Policy Keys
  6. 选择“手动” 。Select Manual .
  7. 使用 IdTokenHintKey 作为“名称” 。For Name , use IdTokenHintKey.
    可能会自动添加前缀 B2C_1A_The prefix B2C_1A_ might be added automatically.
  8. 在“机密”框中,输入之前生成的登录密钥。In the Secret box, enter the sign-in key you generated earlier.
  9. 使用“加密” 作为“密钥用法” 。For Key usage , use Encryption .
  10. 选择“创建” 。Select Create .
  11. 确认已创建密钥 B2C_1A_IdTokenHintKeyConfirm that you've created the key B2C_1A_IdTokenHintKey.

步骤 3.Step 3. 添加 ID 令牌提示技术配置文件Add the ID token hint technical profile

以下技术配置文件会验证令牌并提取声明。The following technical profile validates the token and extracts the claims.

<ClaimsProvider>
  <DisplayName>My ID Token Hint ClaimsProvider</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="IdTokenHint_ExtractClaims">
      <DisplayName> My ID Token Hint TechnicalProfile</DisplayName>
      <Protocol Name="None" />
      <Metadata>
        <Item Key="IdTokenAudience">a489fc44-3cc0-4a78-92f6-e413cd853eae</Item>
        <Item Key="issuer">https://localhost</Item>
      </Metadata>
      <CryptographicKeys>
        <Key Id="client_secret" StorageReferenceId="B2C_1A_IdTokenHintKey" />
      </CryptographicKeys>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="userId" />
      </OutputClaims>
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

步骤 4.Step 4. 准备策略Prepare your policy

完成配置策略步骤。Complete the Configure your policy step.

步骤 5。Step 5. 准备代码Prepare the code

GitHub 示例是一个 ASP.NET Web 应用程序和控制台应用,可生成使用对称密钥签名的 ID 令牌。The GitHub sample is an ASP.NET web application and console app that generates an ID token that is signed using a symmetric key.

使用非对称密钥颁发令牌Issue a token with asymmetric keys

借助非对称密钥,令牌使用 RSA 证书进行签名。With an asymmetric key, the token is signed using RSA certificates. 此应用程序托管 Azure AD B2C 用来验证 ID 令牌的签名的 Open ID Connect 元数据终结点和 JSON Web 密钥 (JWK) 终结点。This application hosts an Open ID Connect metadata endpoint and JSON Web Keys (JWKs) endpoint that is used by Azure AD B2C to validate the signature of the ID token.

令牌颁发者必须提供以下终结点:The token issuer must provide following endpoints:

  • /.well-known/openid-configuration - 一个已知配置终结点,其中包含有关令牌的相关信息,例如令牌颁发者名称和 JWK 终结点的链接。/.well-known/openid-configuration - A well-known configuration endpoint with relevant information about the token, such as the token issuer name and the link to the JWK endpoint.
  • /.well-known/keys - JSON Web 密钥 (JWK) 终结点,其中包含用于对密钥(带有证书的私钥部分)进行签名的公钥。/.well-known/keys - the JSON Web Key (JWK) end point with the public key that is used to sign the key (with the private key part of the certificate).

请参阅 TokenMetadataController.cs .Net MVC 控制器示例。See the TokenMetadataController.cs .Net MVC controller sample.

步骤 1。Step 1. 准备自签名证书Prepare a self-signed certificate

如果你还没有证书,则可以在本操作指南中使用自签名证书。If you don't already have a certificate, you can use a self-signed certificate for this how-to guide. 在 Windows 上,可使用 PowerShell New-SelfSignedCertificate cmdlet 来生成证书。On Windows, you can use PowerShell's New-SelfSignedCertificate cmdlet to generate a certificate.

运行此 PowerShell 命令来生成自签名证书。Run this PowerShell command to generate a self-signed certificate. 根据应用程序的需要修改 -Subject 参数,并修改 Azure AD B2C 租户名称。Modify the -Subject argument as appropriate for your application and Azure AD B2C tenant name. 还可调整 -NotAfter 日期,为证书指定不同的过期日期。You can also adjust the -NotAfter date to specify a different expiration for the certificate.

New-SelfSignedCertificate `
    -KeyExportPolicy Exportable `
    -Subject "CN=yourappname.yourtenant.partner.onmschina.cn" `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -KeyUsage DigitalSignature `
    -NotAfter (Get-Date).AddMonths(12) `
    -CertStoreLocation "Cert:\CurrentUser\My"

步骤 2。Step 2. 添加 ID 令牌提示技术配置文件Add the ID token hint technical profile

以下技术配置文件会验证令牌并提取声明。The following technical profile validates the token and extracts the claims. 将元数据 URI 更改为令牌颁发者已知配置终结点。Change the metadata URI to your token issuer well-known configuration endpoint.

<ClaimsProvider>
  <DisplayName>My ID Token Hint ClaimsProvider</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="IdTokenHint_ExtractClaims">
      <DisplayName> My ID Token Hint TechnicalProfile</DisplayName>
      <Protocol Name="None" />
      <Metadata>
        <!-- Replace with your endpoint location -->
        <Item Key="METADATA">https://your-app.chinacloudsites.cn/.well-known/openid-configuration</Item>
        <Item Key="IdTokenAudience">your_optional_audience</Item> -->
        <!-- <Item Key="issuer">your_optional_token_issuer_override</Item> -->
      </Metadata>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="userId" />
      </OutputClaims>
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

步骤 3.Step 3. 准备策略Prepare your policy

完成配置策略步骤。Complete the Configure your policy step.

步骤 4.Step 4. 准备代码Prepare the code

GitHub 示例 ASP.NET Web 应用程序生成 ID 令牌,并托管在 Azure AD B2C 中使用“id_token_hint”参数所需的元数据终结点。This GitHub sample ASP.NET web application generates ID tokens and hosts the metadata endpoints required to use the "id_token_hint" parameter in Azure AD B2C.

配置策略Configure your policy

对于对称和非对称方法,id_token_hint 技术配置文件会从 GetClaims 类型的业务流程步骤中进行调用,并需要指定信赖方策略的输入声明。For both symmetric and asymmetric approaches, the id_token_hint technical profile is called from an orchestration step with type of GetClaims and needs to specify the input claims of the relying party policy.

  1. 将 IdTokenHint_ExtractClaims 技术配置文件添加到扩展策略。Add the IdTokenHint_ExtractClaims technical profile to your extension policy.

  2. 将以下业务流程步骤作为第一项添加到用户旅程。Add the following orchestration step to your user journey as the first item.

    <OrchestrationStep Order="1" Type="GetClaims" CpimIssuerTechnicalProfileReferenceId="IdTokenHint_ExtractClaims" />
    
  3. 在信赖方策略中,重复在 IdTokenHint_ExtractClaims 技术配置文件中配置的相同输入声明。In your relying party policy, repeat the same input claims you configured in the IdTokenHint_ExtractClaims technical profile. 例如:For example:

    <RelyingParty>
     <DefaultUserJourney ReferenceId="SignUp" />
     <TechnicalProfile Id="PolicyProfile">
       <DisplayName>PolicyProfile</DisplayName>
       <Protocol Name="OpenIdConnect" />
       <InputClaims>
         <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="userId" />
        </InputClaims>
       <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="email" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
        <OutputClaim ClaimTypeReferenceId="identityProvider" />
       </OutputClaims>
       <SubjectNamingInfo ClaimType="sub" />
      </TechnicalProfile>
    </RelyingParty>
    

根据你的业务需求,你可能需要添加令牌验证(例如检查令牌是否到期)、电子邮件地址的格式等。Depending on your business requirements, you might need to add token validations, for example to check token expiry, the format of the email address, and more. 为此,请添加调用声明转换技术配置文件的业务流程步骤。To do so, add orchestration steps that invoke a claims transformation technical profile. 还要添加自断言技术配置文件以显示错误消息。Also add a self-asserted technical profile to present an error message.

创建令牌并对其进行签名Create and sign a token

GitHub 示例演示了如何创建此类令牌,颁发稍后以 id_token_hint 查询字符串参数形式发送的 JWT。The GitHub samples illustrate how to create such a token issue a JWT that later sent as a id_token_hint query string parameter. 下面是一个包含 id_token_hint 参数的授权请求的示例Following is an example of an authorization request with id_token_hint parameter

https://tenant-name.b2clogin.cn/tenant-name.partner.onmschina.cn/B2C_1A_signup_signin/oauth2/v2.0/authorize?client_id=63ba0d17-c4ba-47fd-89e9-31b3c2734339&nonce=defaultNonce&redirect_uri=https%3A%2F%2Fjwt.ms&scope=openid&response_type=id_token&prompt=login&id_token_hint=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaXNwbGF5TmFtZSI6IiBKb2huIFNtaXRoIiwidXNlcklkIjoiam9obi5zQGNvbnRvc28uY29tIiwibmJmIjoxNTk5NDgyNTE1LCJleHAiOjE2MDAwODczMTUsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0IiwiYXVkIjoiYTQ4OWZjNDQtM2NjMC00YTc4LTkyZjYtZTQxM2NkODUzZWFlIn0.nPmLXydI83PQCk5lRBYUZRu_aX58pL1khahHyQuupig

后续步骤Next steps