Azure Active Directory B2C 中的令牌概述Overview of tokens in Azure Active Directory B2C

备注

在 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.

Azure Active Directory B2C (Azure AD B2C) 在处理每个身份验证流时颁发多种安全令牌。Azure Active Directory B2C (Azure AD B2C) emits several types of security tokens as it processes each authentication flow. 本文档说明每种令牌的格式、安全特征和内容。This document describes the format, security characteristics, and contents of each type of token.

令牌类型Token types

Azure AD B2C 支持 OAuth 2.0 和 OpenID Connect 协议,使用令牌进行身份验证和保护对资源的访问。Azure AD B2C supports the OAuth 2.0 and OpenID Connect protocols, which makes use of tokens for authentication and secure access to resources. Azure AD B2C 中使用的所有令牌都是 JSON Web 令牌 (JWT),其中包含有关令牌持有者和使用者的信息断言。All tokens used in Azure AD B2C are JSON web tokens (JWTs) that contain assertions of information about the bearer and the subject of the token.

与 Azure AD B2C 通信时使用以下令牌:The following tokens are used in communication with Azure AD B2C:

  • ID 令牌 - 一个 JWT,其中包含用于验证应用程序中用户的身份的声明。ID token - A JWT that contains claims that you can use to identify users in your application. 在相同应用程序或服务的两个组件之间通信时,会在 HTTP 请求中安全发送此令牌。This token is securely sent in HTTP requests for communication between two components of the same application or service. 可以根据需要使用 ID 令牌中的声明。You can use the claims in an ID token as you see fit. 它们常用于显示帐户信息或者在应用程序中进行访问控制决策。They are commonly used to display account information or to make access control decisions in an application. ID 令牌已签名,但未加密。ID tokens are signed, but they are not encrypted. 当应用程序或 API 收到 ID 令牌时,必须验证签名,证明令牌可信。When your application or API receives an ID token, it must validate the signature to prove that the token is authentic. 应用程序或 API 还必须验证令牌中的一些声明,证明令牌有效。Your application or API must also validate a few claims in the token to prove that it's valid. 根据具体的方案要求,应用程序验证的声明有所不同,但应用程序在每个方案中均须执行某些常见声明验证。Depending on the scenario requirements, the claims validated by an application can vary, but your application must perform some common claim validations in every scenario.
  • 访问令牌 - 一个 JWT,其中包含用于识别已授予的对 API 的权限的声明。Access token - A JWT that contains claims that you can use to identify the granted permissions to your APIs. 访问令牌已签名,但未加密。Access tokens are signed, but they aren't encrypted. 访问令牌用于提供对 API 和资源服务器的访问权限。Access tokens are used to provide access to APIs and resource servers. 当 API 收到访问令牌时,必须验证签名,证明令牌可信。When your API receives an access token, it must validate the signature to prove that the token is authentic. API 还必须验证令牌中的一些声明,证明令牌有效。Your API must also validate a few claims in the token to prove that it is valid. 根据具体的方案要求,应用程序验证的声明有所不同,但应用程序在每个方案中均须执行某些常见声明验证。Depending on the scenario requirements, the claims validated by an application can vary, but your application must perform some common claim validations in every scenario.
  • 刷新令牌 - 刷新令牌用于在 OAuth 2.0 流中获取新的 ID 令牌和访问令牌。Refresh token - Refresh tokens are used to acquire new ID tokens and access tokens in an OAuth 2.0 flow. 它们向应用程序提供代表用户长期访问资源的权限,而无需与这些用户进行交互。They provide your application with long-term access to resources on behalf of users without requiring interaction with those users. 刷新令牌对于应用程序而言是不透明的。Refresh tokens are opaque to your application. 它们由 Azure AD B2C 颁发,且只能由 Azure AD B2C 检查和解释。They are issued by Azure AD B2C and can be inspected and interpreted only by Azure AD B2C. 它们属于长效令牌,但编写应用程序时,不应期望刷新令牌将持续一段特定时间。They are long-lived, but your application shouldn't be written with the expectation that a refresh token will last for a specific period of time. 出于各种原因,可随时验证刷新令牌。Refresh tokens can be invalidated at any moment for a variety of reasons. 让应用程序知道刷新令牌是否有效的唯一方式就是对 Azure AD B2C 发出令牌请求以尝试兑换刷新令牌。The only way for your application to know if a refresh token is valid is to attempt to redeem it by making a token request to Azure AD B2C. 使用刷新令牌兑换新的令牌时,会在令牌响应中收到新的刷新令牌。When you redeem a refresh token for a new token, you receive a new refresh token in the token response. 保存新的刷新令牌。Save the new refresh token. 它会替代以前在请求中使用的刷新令牌。It replaces the refresh token that you previously used in the request. 此操作有助于保证刷新令牌尽可能长期保持有效。This action helps guarantee that your refresh tokens remain valid for as long as possible. 请注意,使用 PKCE 授权代码流的单页应用程序的刷新令牌生存期始终为 24 小时。Note that single-page applications using the authorization code flow with PKCE always have a refresh token lifetime of 24 hours. 详细了解浏览器中的刷新令牌的安全影响Learn more about the security implications of refresh tokens in the browser.

终结点Endpoints

已注册的应用程序接收令牌,并通过向这些终结点发送请求来与 Azure AD B2C 通信:A registered application receives tokens and communicates with Azure AD B2C by sending requests to these endpoints:

  • https://<tenant-name>.b2clogin.cn/<tenant-name>.partner.onmschina.cn/<policy-name>/oauth2/v2.0/authorize
  • https://<tenant-name>.b2clogin.cn/<tenant-name>.partner.onmschina.cn/<policy-name>/oauth2/v2.0/token

应用程序从 Azure AD B2C 接收的安全令牌可能来自 /authorize/token 终结点。Security tokens that your application receives from Azure AD B2C can come from the /authorize or /token endpoints. /authorize 终结点获取 ID 令牌时,将通过使用隐式流完成此操作,该流通常用于供用户登录到基于 JavaScript 的 Web 应用程序。When ID tokens are acquired from the /authorize endpoint, it's done using the implicit flow, which is often used for users signing in to JavaScript-based web applications. /token 终结点获取 ID 令牌时,将通过使用授权代码流完成此操作,该流使令牌对浏览器保持隐藏。When ID tokens are acquired from the /token endpoint, it's done using the authorization code flow, which keeps the token hidden from the browser.

声明Claims

使用 Azure AD B2C 时,必须对令牌内容有精细的控制。When you use Azure AD B2C, you have fine-grained control over the content of your tokens. 可以配置用户流自定义策略,在声明中发送应用程序所需的特定用户数据集。You can configure user flows and custom policies to send certain sets of user data in claims that are required for your application. 这些声明可以包含标准属性,例如 displayNameemailAddressThese claims can include standard properties such as displayName and emailAddress. 应用程序可以使用这些声明来安全地对用户和请求进行身份验证。Your applications can use these claims to securely authenticate users and requests.

ID 令牌中的声明不按任何特定顺序返回。The claims in ID tokens are not returned in any particular order. 新的声明可以在任何时候引入 ID 令牌。New claims can be introduced in ID tokens at any time. 引入新的声明时,应用程序不应中断。Your application shouldn't break as new claims are introduced. 还可以在声明中包含自定义用户属性You can also include custom user attributes in your claims.

下表列出了 Azure AD B2C 颁发的 ID 令牌和访问令牌中预期包含的声明。The following table lists the claims that you can expect in ID tokens and access tokens issued by Azure AD B2C.

名称Name 声明Claim 示例值Example value 说明Description
读者Audience aud 90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 标识令牌的目标接收方。Identifies the intended recipient of the token. 对于 Azure AD B2C,受众是在应用程序 ID。For Azure AD B2C, the audience is the application ID. 应用程序应该验证此值并拒绝不匹配的令牌。Your application should validate this value and reject the token if it doesn't match. 受众是资源的同义词。Audience is synonymous with resource.
颁发者Issuer iss https://<tenant-name>.b2clogin.cn/775527ff-9a37-4307-8b3d-cc311f58d925/v2.0/ 标识构造并返回令牌的安全令牌服务 (STS)。Identifies the security token service (STS) that constructs and returns the token. 它还标识在其中进行用户身份验证的目录。It also identifies the directory in which the user was authenticated. 应用程序应该验证颁发者声明,以确保令牌来自适当的终结点。Your application should validate the issuer claim to make sure that the token came from the appropriate endpoint.
颁发时间Issued at iat 1438535543 颁发令牌的时间,以纪元时间表示。The time at which the token was issued, represented in epoch time.
过期时间Expiration time exp 1438539443 令牌失效的时间,以纪元时间表示。The time at which the token becomes invalid, represented in epoch time. 应用程序应该使用此声明来验证令牌生存期的有效性。Your application should use this claim to verify the validity of the token lifetime.
生效时间Not before nbf 1438535543 令牌生效的时间,以纪元时间表示。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. 应用程序应该使用此声明来验证令牌生存期的有效性。Your application should use this claim to verify the validity of the token lifetime.
版本Version ver 1.0 Azure AD B2C 定义的 ID 令牌版本。The version of the ID token, as defined by Azure AD B2C.
代码哈希Code hash c_hash SGCPtt01wxwfgnYZy2VJtQ 仅当令牌随 OAuth 2.0 授权代码一起颁发时,代码哈希才包含在 ID 令牌中。A code hash included in an ID token only when the token is issued together with an OAuth 2.0 authorization code. 代码哈希可用于验证授权代码的真实性。A code hash can be used to validate the authenticity of an authorization code. 有关如何执行此验证的详细信息,请参阅 OpenID Connect 规范For more information about how to perform this validation, see the OpenID Connect specification.
访问令牌哈希Access token hash at_hash SGCPtt01wxwfgnYZy2VJtQ 仅当令牌随 OAuth 2.0 访问令牌一起颁发时,访问令牌哈希才包含在 ID 令牌中。An access token hash included in an ID token only when the token is issued together with an OAuth 2.0 access token. 访问令牌哈希可用于验证访问令牌的真实性。An access token hash can be used to validate the authenticity of an access token. 有关如何执行此验证的详细信息,请参阅 OpenID Connect 规范For more information about how to perform this validation, see the OpenID Connect specification
NonceNonce nonce 12345 Nonce 是缓和令牌重放攻击的策略。A nonce is a strategy used to mitigate token replay attacks. 应用程序可通过使用 nonce 查询参数,在授权请求中指定 nonce。Your application can specify a nonce in an authorization request by using the nonce query parameter. 在请求中提供的值将仅在 ID 令牌的 nonce 声明中发出(未经修改)。The value you provide in the request is emitted unmodified in the nonce claim of an ID token only. 此声明可让应用程序根据请求中指定的值验证该值。This claim allows your application to verify the value against the value specified on the request. 应用程序应该在 ID 令牌验证过程中执行这项验证。Your application should perform this validation during the ID token validation process.
使用者Subject sub 884408e1-2918-4cz0-b12d-3aa027d7563b 令牌针对其断言信息的主体,例如应用程序的用户。The principal about which the token asserts information, such as the user of an application. 此值固定不变,无法重新分配或重复使用。This value is immutable and cannot be reassigned or reused. 可以使用它来安全地执行授权检查,例如,当使用令牌访问资源时。It can be used to perform authorization checks safely, such as when the token is used to access a resource. 默认情况下,将使用目录中用户的对象 ID 填充使用者声明。By default, the subject claim is populated with the object ID of the user in the directory.
身份验证上下文类引用Authentication context class reference acr 不适用Not applicable 仅与旧策略配合使用。Used only with older policies.
信任框架策略Trust framework policy tfp b2c_1_signupsignin1 用于获取 ID 令牌的策略名称。The name of the policy that was used to acquire the ID token.
身份验证时间Authentication time auth_time 1438535543 用户最后一次输入凭据的时间,以新纪元时间表示。The time at which a user last entered credentials, represented in epoch time. 该身份验证是全新登录、单一登录 (SSO) 会话还是其他登录类型之间没有区别。There is no discrimination between that authentication being a fresh sign-in, a single sign-on (SSO) session, or another sign-in type. auth_time 是应用程序(或用户)上次针对 Azure AD B2C 发起身份验证尝试的时间。The auth_time is the last time the application (or user) initiated an authentication attempt against Azure AD B2C. 不区分用于身份验证的方法。The method used to authenticate is not differentiated.
范围Scope scp Read 授予访问令牌对资源的权限。The permissions granted to the resource for an access token. 多个授予的权限以空格分隔。Multiple granted permissions are separated by a space.
授权方Authorized Party azp 975251ed-e4f5-4efd-abcb-5f1a8f566ab7 发起请求的客户端应用程序的 应用程序 IDThe application ID of the client application that initiated the request.

配置Configuration

以下是用于管理 Azure AD B2C 发出的安全令牌的生存期的属性:The following properties are used to manage lifetimes of security tokens emitted by Azure AD B2C:

  • 访问令牌和 ID 令牌生存期(分钟) - 用于获取受保护资源的访问权限的 OAuth 2.0 持有者令牌的生存期。Access & ID token lifetimes (minutes) - The lifetime of the OAuth 2.0 bearer token used to gain access to a protected resource. 默认值为 60 分钟。The default is 60 minutes. 最小值为 5 分钟(含)。The minimum (inclusive) is 5 minutes. 最大值为 1440 分钟(含)。The maximum (inclusive) is 1440 minutes.

  • 刷新令牌生存期(天) - 可以使用刷新令牌获取新的访问令牌或 ID 令牌之前的最大时限。Refresh token lifetime (days) - The maximum time period before which a refresh token can be used to acquire a new access or ID token. 该时限还包括为应用程序授予了 offline_access 范围时获取新刷新令牌的最大时限。The time period also covers acquiring a new refresh token if your application has been granted the offline_access scope. 默认值为 14 天。The default is 14 days. 最小值为 1 天(含)。The minimum (inclusive) is one day. 最大值为 90 天(含)。The maximum (inclusive) is 90 days.

  • 刷新令牌的滑动窗口生存期(天) - 此时限过后,强制用户重新进行身份验证,不考虑应用程序获取的最新刷新令牌的有效期。Refresh token sliding window lifetime (days) - After this time period elapses the user is forced to reauthenticate, irrespective of the validity period of the most recent refresh token acquired by the application. 仅在此开关设为“有限”时该属性才可用。It can only be provided if the switch is set to Bounded. 它的值必须大于或等于 刷新令牌生存期(天) 的值。It needs to be greater than or equal to the Refresh token lifetime (days) value. 如果此开关设置为“无限”,则无法提供特定值。If the switch is set to Unbounded, you cannot provide a specific value. 默认值为 90 天。The default is 90 days. 最小值为 1 天(含)。The minimum (inclusive) is one day. 最大值为 365 天(含)。The maximum (inclusive) is 365 days.

以下用例是使用这些属性实现的:The following use cases are enabled using these properties:

  • 只要用户在移动应用程序上持续保持活动状态,允许该用户无限期地保持登录此应用程序。Allow a user to stay signed in to a mobile application indefinitely, as long as the user is continually active on the application. 可将登录用户流中的“刷新令牌的滑动窗口生存期(天)”开关设为“无限”。You can set Refresh token sliding window lifetime (days) to Unbounded in your sign-in user flow.
  • 通过设置合适的访问令牌生存期来满足行业的安全性和合规性要求。Meet your industry's security and compliance requirements by setting the appropriate access token lifetimes.

这些设置不适用于密码重置用户流。These settings are not available for password reset user flows.

兼容性Compatibility

以下属性用于管理令牌兼容性The following properties are used to manage token compatibility:

  • 颁发者 (iss) 声明 - 此属性标识颁发令牌的 Azure AD B2C 租户。Issuer (iss) claim - This property identifies the Azure AD B2C tenant that issued the token. 默认值为 https://<domain>/{B2C tenant GUID}/v2.0/The default value is https://<domain>/{B2C tenant GUID}/v2.0/. https://<domain>/tfp/{B2C tenant GUID}/{Policy ID}/v2.0/ 值包含令牌请求中使用的 Azure AD B2C 租户和用户流的 ID。The value of https://<domain>/tfp/{B2C tenant GUID}/{Policy ID}/v2.0/ includes IDs for both the Azure AD B2C tenant and the user flow that was used in the token request. 如果应用程序或库需要 Azure AD B2C 才能符合 OpenID Connect Discovery 1.0 规范,请使用此值。If your application or library needs Azure AD B2C to be compliant with the OpenID Connect Discovery 1.0 spec, use this value.

  • 使用者 (sub) 声明 - 此属性标识令牌断言其信息的实体。Subject (sub) claim - This property identifies the entity for which the token asserts information. 默认值为 ObjectID,即在令牌的 sub 声明中填充用户的对象 ID。The default value is ObjectID, which populates the sub claim in the token with the object ID of the user. Not supported 值仅供用于实现后向兼容。The value of Not supported is only provided for backward-compatibility. 建议尽快改用 ObjectIDIt's recommended that you switch to ObjectID as soon as you are able to.

  • 表示策略 ID 的声明 - 此属性标识要在其中填充令牌请求中使用的策略名称的声明类型。Claim representing policy ID - This property identifies the claim type into which the policy name used in the token request is populated. 默认值为 tfpThe default value is tfp. acr 值仅供用于实现后向兼容。The value of acr is only provided for backward-compatibility.

直通Pass-through

用户旅程开始时,Azure AD B2C 会从标识提供者处收到一个访问令牌。When a user journey starts, Azure AD B2C receives an access token from an identity provider. Azure AD B2C 使用该令牌来检索有关用户的信息。Azure AD B2C uses that token to retrieve information about the user. 在用户流中启用声明在自定义策略中定义声明即可将该令牌传递给你在 Azure AD B2C 中注册的应用程序。You enable a claim in your user flow or define a claim in your custom policy to pass the token through to the applications that you register in Azure AD B2C. 应用程序必须使用建议的用户流才能利用将令牌作为声明传递的优势。Your application must be using a recommended user flow to take advantage of passing the token as a claim.

Azure AD B2C 当前仅支持传递 OAuth 2.0 标识提供者的访问令牌。Azure AD B2C currently only supports passing the access token of OAuth 2.0 identity providers. 对于所有其他标识提供者,声明将返回空白。For all other identity providers, the claim is returned blank.

验证Validation

若要验证令牌,应用程序应检查令牌的签名和声明。To validate a token, your application should check both the signature and claims of the token. 许多开放源代码库都可用于验证 JWT,具体取决于首选语言。Many open-source libraries are available for validating JWTs, depending on your preferred language. 建议浏览这些选项,而不是实施自己的验证逻辑。It's recommended that you explore those options rather than implement your own validation logic.

验证签名Validate signature

JWT 包含三段:标头、主体和签名。 A JWT contains three segments, a header, a body, and a signature. 签名段可用于验证令牌的真实性,使令牌可获得应用程序的信任。The signature segment can be used to validate the authenticity of the token so that it can be trusted by your application. Azure AD B2C 令牌使用行业标准非对称式加密算法(例如 RSA 256)进行签名。Azure AD B2C tokens are signed by using industry-standard asymmetric encryption algorithms, such as RSA 256.

令牌标头包含用于签名令牌的密钥和加密方法的相关信息:The header of the token contains information about the key and encryption method used to sign the token:

{
        "typ": "JWT",
        "alg": "RS256",
        "kid": "GvnPApfWMdLRi8PDmisFn7bprKg"
}

alg 声明的值是用来为令牌签名的算法。The value of the alg claim is the algorithm that was used to sign the token. kid 声明的值是用来为令牌签名的公钥。The value of the kid claim is the public key that was used to sign the token. 在任何给定时间,Azure AD B2C 都可使用一组公钥-私钥对中的任意一个对令牌签名。At any given time, Azure AD B2C can sign a token by using any one of a set of public-private key pairs. Azure AD B2C 定期轮换可能一组的密钥。Azure AD B2C rotates the possible set of keys periodically. 应将应用程序编写成自动处理这些密钥更改。Your application should be written to handle those key changes automatically. 对 Azure AD B2C 所用公钥的更新进行检查的合理频率为每 24 小时一次。A reasonable frequency to check for updates to the public keys used by Azure AD B2C is every 24 hours. 若要处理意外的密钥更改,你的应用程序应当编写为在收到意外的 kid 值时重新检索公钥。To handle unexpected key changes, your application should be written to re-retrieve the public keys if it receives an unexpected kid value.

Azure AD B2C 具有 OpenID Connect 元数据终结点。Azure AD B2C has an OpenID Connect metadata endpoint. 使用此终结点,应用程序可以在运行时请求有关 Azure AD B2C 的信息。Using this endpoint, applications can request information about Azure AD B2C at runtime. 此信息包括终结点、令牌内容和令牌签名密钥。This information includes endpoints, token contents, and token signing keys. Azure AD B2C 租户针对策略包含一个 JSON 元数据文档。Your Azure AD B2C tenant contains a JSON metadata document for each policy. 元数据文档是包含多条有用信息的 JSON 对象。The metadata document is a JSON object that contains several useful pieces of information. 元数据包含 jwks_uri,它提供用于对令牌签名的公钥集位置。The metadata contains jwks_uri, which gives the location of the set of public keys that are used to sign tokens. 在此处提供该位置,但最好使用元数据文档并分析 jwks_uri 来动态提取位置:That location is provided here, but it's best to fetch the location dynamically by using the metadata document and parsing jwks_uri:

https://contoso.b2clogin.cn/contoso.partner.onmschina.cn/b2c_1_signupsignin1/discovery/v2.0/keys

位于此 URL 的 JSON 文档包含将在特定时间点使用的所有公钥信息。The JSON document located at this URL contains all the public key information in use at a particular moment. 应用可以使用 JWT 标头中的 kid 声明,选择用于签名特定令牌的 JSON 文档中的公钥。Your app can use the kid claim in the JWT header to select the public key in the JSON document that is used to sign a particular token. 然后,可以使用正确的公钥和指定的算法来执行签名验证。It can then perform signature validation by using the correct public key and the indicated algorithm.

contoso.partner.onmschina.cn 租户中的 B2C_1_signupsignin1 策略的元数据文档位于:The metadata document for the B2C_1_signupsignin1 policy in the contoso.partner.onmschina.cn tenant is located at:

https://contoso.b2clogin.cn/contoso.partner.onmschina.cn/b2c_1_signupsignin1/v2.0/.well-known/openid-configuration

若要确定对令牌签名所用的策略(以及请求元数据的位置),有两个选择。To determine which policy was used to sign a token (and where to go to request the metadata), you have two options. 首先,策略名称包含在令牌的 tfp(默认)或 acr 声明(按照配置)中。First, the policy name is included in the tfp (default) or acr claim (as configured) in the token. 可以通过对主体进行 Base-64 解码,并反序列化生成的 JSON 字符串,从而分析 JWT 主体中的声明。You can parse claims out of the body of the JWT by base-64 decoding the body and deserializing the JSON string that results. tfpacr 声明是用于颁发令牌的策略的名称。The tfp or acr claim is the name of the policy that was used to issue the token. 另一个方法是在发出请求时在 state 参数的值中对策略进行编码,并对其进行解码以确定使用的策略。The other option is to encode the policy in the value of the state parameter when you issue the request, and then decode it to determine which policy was used. 任意一种方法均有效。Either method is valid.

关于如何执行签名验证的说明已超出了本文档的讨论范围。A description of how to perform signature validation is outside the scope of this document. 有许多开源库可帮助验证令牌。Many open-source libraries are available to help you validate a token.

验证声明Validate claims

应用程序或 API 收到 ID 令牌时,还应对 ID 令牌中的声明执行几项检查。When your applications or API receives an ID token, it should also perform several checks against the claims in the ID token. 应检查以下声明:The following claims should be checked:

  • audience - 验证是否计划向应用程序提供 ID 令牌。audience - Verifies that the ID token was intended to be given to your application.
  • not beforeexpiration time - 验证 ID 令牌是否未过期。not before and expiration time - Verifies that the ID token hasn't expired.
  • issuer - 验证令牌是否确实由 Azure AD B2C 向应用程序颁发。issuer - Verifies that the token was issued to your application by Azure AD B2C.
  • nonce - 缓解令牌重放攻击的策略。nonce - A strategy for token replay attack mitigation.

有关应用程序应该执行的验证的完整列表,请参阅 OpenID Connect 规范For a full list of validations your application should perform, refer to the OpenID Connect specification.

后续步骤Next steps

详细了解如何使用访问令牌Learn more about how to use access tokens.