在 Azure Active Directory B2C 中使用 OpenID Connect 进行 Web 登录Web sign-in with OpenID Connect in Azure Active Directory B2C

OpenID Connect 是构建在 OAuth 2.0 基础之上的身份验证协议,可用于将用户安全登录到 Web 应用程序。OpenID Connect is an authentication protocol, built on top of OAuth 2.0, that can be used to securely sign users in to web applications. 通过使用 OpenID Connect 的 Azure Active Directory B2C (Azure AD B2C) 实现,可以将 Web 应用程序中的注册、登录和其他标识管理体验转移到 Azure Active Directory (Azure AD) 中。By using the Azure Active Directory B2C (Azure AD B2C) implementation of OpenID Connect, you can outsource sign-up, sign-in, and other identity management experiences in your web applications to Azure Active Directory (Azure AD). 本指南演示如何使用与语言无关的方式执行此操作。This guide shows you how to do so in a language-independent manner. 介绍在不使用我们的任何开放源代码库的情况下,如何发送和接收 HTTP 消息。It describes how to send and receive HTTP messages without using any of our open-source libraries.

OpenID Connect 扩展了 OAuth 2.0 授权协议,将其用作身份验证协议。OpenID Connect extends the OAuth 2.0 authorization protocol for use as an authentication protocol. 使用此身份验证协议可以执行单一登录。This authentication protocol allows you to perform single sign-on. 它引入了 ID 令牌的概念,可让客户端验证用户的标识,并获取有关用户的基本配置文件信息。It introduces the concept of an ID token, which allows the client to verify the identity of the user and obtain basic profile information about the user.

因为 OpenID Connect 扩展了 OAuth 2.0,因此,它还能使应用程序安全地获取访问令牌。Because it extends OAuth 2.0, it also enables applications to securely acquire access tokens. 可以使用 access_token 访问由授权服务器保护的资源。You can use access tokens to access resources that are secured by an authorization server. 如果要生成的 Web 应用程序托管在服务器中并通过浏览器访问,我们建议使用 OpenID Connect。OpenID Connect is recommended if you're building a web application that's hosted on a server and accessed through a browser. 有关令牌的详细信息,请参阅 Azure Active Directory B2C 中的令牌概述For more information about tokens, see the Overview of tokens in Azure Active Directory B2C

Azure AD B2C 扩展了标准 OpenID Connect 协议,使其功能远远超出了简单的身份验证和授权。Azure AD B2C extends the standard OpenID Connect protocol to do more than simple authentication and authorization. 它引入了用户流参数,可让你使用 OpenID Connect 向应用程序添加注册、登录和配置文件管理等用户体验。It introduces the user flow parameter, which enables you to use OpenID Connect to add user experiences to your application, such as sign-up, sign-in, and profile management.

发送身份验证请求Send authentication requests

当 Web 应用程序需要对用户进行身份验证并运行用户流时,它可以将用户定向到 /authorize 终结点。When your web application needs to authenticate the user and run a user flow, it can direct the user to the /authorize endpoint. 用户可以根据用户流执行操作。The user takes action depending on the user flow.

在此请求中,客户端指示需要在 scope 参数中从用户获取的权限,并指定要运行的用户流。In this request, the client indicates the permissions that it needs to acquire from the user in the scope parameter, and specifies the user flow to run. 若要了解该请求的工作原理,请尝试将该请求粘贴到浏览器中并运行它。To get a feel for how the request works, try pasting the request into a browser and running it. {tenant} 替换为租户的名称。Replace {tenant} with the name of your tenant. 90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 替换为之前在租户中注册的应用程序的应用程序 ID。Replace 90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 with the app ID of the application you've previously registered in your tenant. 此外,将策略名称 ({policy}) 更改为租户中的策略名称,例如 b2c_1_sign_inAlso change the policy name ({policy}) to the policy name that you have in your tenant, for example b2c_1_sign_in.

GET https://{tenant}.b2clogin.cn/{tenant}.partner.onmschina.cn/{policy}/oauth2/v2.0/authorize?
client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
&response_type=code+id_token
&redirect_uri=https%3A%2F%2Faadb2cplayground.chinacloudsites.cn%2F
&response_mode=form_post
&scope=openid%20offline_access
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=12345
参数Parameter 必须Required 说明Description
{tenant}{tenant} Yes Azure AD B2C 租户的名称Name of your Azure AD B2C tenant
{policy}{policy} Yes 要运行的用户流。The user flow to be run. 指定在 Azure AD B2C 租户中创建的用户流的名称。Specify the name of a user flow you've created in your Azure AD B2C tenant. 例如:b2c_1_sign_inb2c_1_sign_upb2c_1_edit_profileFor example: b2c_1_sign_in, b2c_1_sign_up, or b2c_1_edit_profile.
client_idclient_id Yes Azure 门户分配给应用程序的应用程序 ID。The application ID that the Azure portal assigned to your application.
noncenonce Yes 由应用程序生成且包含在请求中的值,以声明方式包含在生成的 ID 令牌中。A value included in the request (generated by the application) that is included in the resulting ID token as a claim. 应用程序接着便可确认此值,以减少令牌重新执行攻击。The application can then verify this value to mitigate token replay attacks. 此值通常是随机的唯一字符串,可用以识别请求的来源。The value is typically a randomized unique string that can be used to identify the origin of the request.
response_typeresponse_type Yes 必须包含 OpenID Connect 的 ID 令牌。Must include an ID token for OpenID Connect. 如果 Web 应用程序还需要使用令牌来调用 Web API,则可以使用 code+id_tokenIf your web application also needs tokens for calling a web API, you can use code+id_token.
scopescope Yes 范围的空格分隔列表。A space-separated list of scopes. openid 作用域表示允许使用 ID 令牌的形式使用户登录并获取有关用户的数据。The openid scope indicates a permission to sign in the user and get data about the user in the form of ID tokens. offline_access 范围对 Web 应用程序是可选的。The offline_access scope is optional for web applications. 它表示应用程序需要使用刷新令牌来长期访问资源。It indicates that your application will need a refresh token for extended access to resources.
promptprompt No 需要的用户交互类型。The type of user interaction that's required. 此时唯一有效的值为 login,这会强制用户在该请求上输入其凭据。The only valid value at this time is login, which forces the user to enter their credentials on that request.
redirect_uriredirect_uri No 应用程序的 redirect_uri 参数,应用程序可在此发送及接收身份验证响应。The redirect_uri parameter of your application, where authentication responses can be sent and received by your application. 它必须完全匹配在 Azure 门户中注册的其中一个 redirect_uri 参数,但必须经过 URL 编码。It must exactly match one of the redirect_uri parameters that you registered in the Azure portal, except that it must be URL encoded.
response_moderesponse_mode No 将生成的授权代码发回到应用程序所用的方法。The method that is used to send the resulting authorization code back to your application. 这可以是 queryform_postfragmentIt can be either query, form_post, or fragment. 建议使用 form_post 响应模式以获得最佳安全性。The form_post response mode is recommended for best security.
statestate No 同时随令牌响应返回的请求中所包含的值。A value included in the request that's also returned in the token response. 可以是所需的任何内容的字符串。It can be a string of any content that you want. 随机生成的唯一值通常用于防止跨站点请求伪造攻击。A randomly generated unique value is typically used for preventing cross-site request forgery attacks. 该状态也用于在身份验证请求出现之前,在应用程序中编码用户的状态信息,例如用户之前所在的页面。The state is also used to encode information about the user's state in the application before the authentication request occurred, such as the page they were on.

此时,要求用户完成工作流。At this point, the user is asked to complete the workflow. 用户可能需要输入其用户名和密码、用社交标识登录,或注册目录。The user might have to enter their username and password, sign in with a social identity, or sign up for the directory. 可能还可任何其他若干步骤,具体取决于如何定义用户流。There could be any other number of steps depending on how the user flow is defined.

用户完成用户流后,会使用 response_mode 参数中指定的方法,将响应返回到 redirect_uri 参数中指定的应用程序。After the user completes the user flow, a response is returned to your application at the indicated redirect_uri parameter, by using the method that's specified in the response_mode parameter. 对于上述每种情况,响应均相同,而与用户流无关。The response is the same for each of the preceding cases, independent of the user flow.

使用 response_mode=fragment 的成功的响应如下所示:A successful response using response_mode=fragment would look like:

GET https://aadb2cplayground.chinacloudsites.cn/#
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
&state=arbitrary_data_you_can_receive_in_the_response
参数Parameter 说明Description
id_tokenid_token 应用程序请求的 ID 令牌。The ID token that the application requested. 可以使用 ID 令牌验证用户的标识,开始与用户建立会话。You can use the ID token to verify the user's identity and begin a session with the user.
codecode 如果使用了 response_type=code+id_token,则为应用程序请求的授权代码。The authorization code that the application requested, if you used response_type=code+id_token. 应用程序可以使用该授权代码请求目标资源的访问令牌。The application can use the authorization code to request an access token for a target resource. 授权代码通常在约 10 分钟后即会过期。Authorization codes typically expire after about 10 minutes.
statestate 如果请求中包含 state 参数,响应中就应该出现相同的值。If a state parameter is included in the request, the same value should appear in the response. 应用程序需验证请求和响应中的 state 值是否相同。The application should verify that the state values in the request and response are identical.

错误响应也可能会被发送到 redirect_uri 参数,以便应用程序对它们进行恰当的处理:Error responses can also be sent to the redirect_uri parameter so that the application can handle them appropriately:

GET https://aadb2cplayground.chinacloudsites.cn/#
error=access_denied
&error_description=the+user+canceled+the+authentication
&state=arbitrary_data_you_can_receive_in_the_response
参数Parameter 说明Description
errorerror 一个代码,可用于对发生的错误类型进行分类。A code that can be used to classify the types of errors that occur.
error_descriptionerror_description 帮助识别身份验证错误根本原因的特定错误消息。A specific error message that can help identify the root cause of an authentication error.
statestate 如果请求中包含 state 参数,响应中就应该出现相同的值。If a state parameter is included in the request, the same value should appear in the response. 应用程序需验证请求和响应中的 state 值是否相同。The application should verify that the state values in the request and response are identical.

验证 ID 令牌Validate the ID token

仅收到一个 ID 令牌并不表示可以对用户进行身份验证。Just receiving an ID token is not enough to authenticate the user. 根据应用程序的要求验证 ID 令牌的签名和令牌中的声明。Validate the ID token's signature and verify the claims in the token per your application's requirements. Azure AD B2C 使用 JSON Web 令牌 (JWT) 和公钥加密对令牌进行签名并验证其是否有效。Azure AD B2C uses JSON Web Tokens (JWTs) and public key cryptography to sign tokens and verify that they are valid. 有许多开放源代码库可用于验证 JWT,具体取决于首选语言。There are many open-source libraries that are available for validating JWTs, depending on your language of preference. 我们建议使用这些库,而不是实施自己的验证逻辑。We recommend exploring those options rather than implementing your own validation logic.

Azure AD B2C 具有 OpenID Connect 元数据终结点,允许应用程序在运行时获取有关 Azure AD B2C 的信息。Azure AD B2C has an OpenID Connect metadata endpoint, which allows an application to get information about Azure AD B2C at runtime. 此信息包括终结点、令牌内容和令牌签名密钥。This information includes endpoints, token contents, and token signing keys. B2C 租户中的每个用户流都有一个 JSON 元数据文档。There is a JSON metadata document for each user flow in your B2C tenant. 例如,fabrikamb2c.partner.onmschina.cnb2c_1_sign_in 用户流的元数据文档位于:For example, the metadata document for the b2c_1_sign_in user flow in fabrikamb2c.partner.onmschina.cn is located at:

https://fabrikamb2c.b2clogin.cn/fabrikamb2c.partner.onmschina.cn/b2c_1_sign_in/v2.0/.well-known/openid-configuration

此配置文档的一个属性为 jwks_uri,对于相同用户流,该属性的值为:One of the properties of this configuration document is jwks_uri, whose value for the same user flow would be:

https://fabrikamb2c.b2clogin.cn/fabrikamb2c.partner.onmschina.cn/b2c_1_sign_in/discovery/v2.0/keys

若要确定对 ID 令牌进行签名所使用的用户流(以及从何处获取元数据),可以使用两种方法。To determine which user flow was used in signing an ID token (and from where to get the metadata), you have two options. 第一种方法,用户流名称包含在 ID 令牌的 acr 声明中。First, the user flow name is included in the acr claim in the ID token. 另一个方法是在发出请求时在 state 参数的值中对用户流进行编码,然后对其进行解码以确定使用的用户流。Your other option is to encode the user flow in the value of the state parameter when you issue the request, and then decode it to determine which user flow was used. 任意一种方法均有效。Either method is valid.

从 OpenID Connect 元数据终结点获取元数据文档后,可以使用 RSA-256 公钥来验证 ID 令牌的签名。After you've acquired the metadata document from the OpenID Connect metadata endpoint, you can use the RSA 256 public keys to validate the signature of the ID token. 此终结点上可能列出多个密钥,每个密钥使用 kid 声明进行标识。There might be multiple keys listed at this endpoint, each identified by a kid claim. ID 令牌的标头还包含 kid 声明,该声明指示哪个密钥用于对 ID 令牌进行签名。The header of the ID token also contains a kid claim, which indicates which of these keys was used to sign the ID token.

若要从 Azure AD B2C 验证令牌,需要使用指数 (e) 和模数 (n) 生成公钥。To verify the tokens from Azure AD B2C, you need to generate the public key using the exponent(e) and modulus(n). 需要确定如何在相应的编程语言中执行此操作。You need to determine how to do this in your respective programming language accordingly. 可在以下网页中找到有关使用 RSA 协议生成公钥的官方文档: https://tools.ietf.org/html/rfc3447#section-3.1The official documentation on Public Key generation with the RSA protocol can be found here: https://tools.ietf.org/html/rfc3447#section-3.1

验证 ID 令牌的签名后,还有几项声明需要验证。After you've validated the signature of the ID token, there are several claims that you need to verify. 例如:For instance:

  • 验证 nonce 声明以防止令牌重放攻击。Validate the nonce claim to prevent token replay attacks. 其值应为在登录请求中指定的内容。Its value should be what you specified in the sign-in request.
  • 验证 aud 声明以确保已为应用程序颁发 ID 令牌。Validate the aud claim to ensure that the ID token was issued for your application. 其值应为应用程序的 ID。Its value should be the application ID of your application.
  • 验证 iatexp 声明以确保 ID 令牌未过期。Validate the iat and exp claims to make sure that the ID token hasn't expired.

此外,还需要执行更多的一些验证。There are also several more validations that you should perform. OpenID Connect 核心规范中详细介绍了验证。根据情况,可能还希望验证其他声明。The validations are described in detail in the OpenID Connect Core Spec. You might also want to validate additional claims, depending on your scenario. 一些常见的验证包括:Some common validations include:

  • 确保用户/组织已注册应用程序。Ensuring that the user/organization has signed up for the application.
  • 确保用户拥有正确的授权/权限。Ensuring that the user has proper authorization/privileges.
  • 确保执行了一定强度的身份验证,例如 Azure 多重身份验证。Ensuring that a certain strength of authentication has occurred, such as Azure Multi-Factor Authentication.

验证 ID 令牌后,可以开始与用户的会话。After you validate the ID token, you can begin a session with the user. 在应用程序中,可以使用 ID 令牌中的声明来获取用户的相关信息。You can use the claims in the ID token to obtain information about the user in your application. 此信息的用途包括显示、记录和授权。Uses for this information include display, records, and authorization.

获取令牌Get a token

如果仅需要 Web 应用程序运行用户流,则可以跳过下面几个部分。If you need your web application to only run user flows, you can skip the next few sections. 这些部分仅适用于需要对 Web API 进行验证的调用,以及受到 Azure AD B2C 保护的 Web 应用程序。These sections are applicable only to web applications that need to make authenticated calls to a web API and are also protected by Azure AD B2C.

通过将 POST 请求发送到 /token 终结点,可以将获取的授权代码(通过 response_type=code+id_token 获取)兑换为所需资源的令牌。You can redeem the authorization code that you acquired (by using response_type=code+id_token) for a token to the desired resource by sending a POST request to the /token endpoint. 在 Azure AD B2C 中,可以像往常一样通过在请求中指定其他 API 的范围来为这些 API 请求访问令牌In Azure AD B2C, you can request access tokens for other APIs as usual by specifying their scope(s) in the request.

还可以按照将应用的客户端 ID 用作所请求范围(这将导致具有该客户端 ID 的访问令牌作为“受众”)的约定,为应用自己的后端 Web API 请求访问令牌:You can also request an access token for your app's own back-end Web API by convention of using the app's client ID as the requested scope (which will result in an access token with that client ID as the "audience"):

POST {tenant}.partner.onmschina.cn/{policy}/oauth2/v2.0/token HTTP/1.1
Host: {tenant}.b2clogin.cn
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:wg:oauth:2.0:oob
参数Parameter 必须Required 说明Description
{tenant}{tenant} Yes Azure AD B2C 租户的名称Name of your Azure AD B2C tenant
{policy}{policy} Yes 用于获取授权代码的用户流。The user flow that was used to acquire the authorization code. 无法在此请求中使用不同的用户流。You can't use a different user flow in this request. 将此参数添加到查询字符串中,而不是添加到 POST 正文中。Add this parameter to the query string, not to the POST body.
client_idclient_id Yes Azure 门户分配给应用程序的应用程序 ID。The application ID that the Azure portal assigned to your application.
client_secretclient_secret 是,在 Web 应用中Yes, in Web Apps Azure 门户中生成的应用程序机密。The application secret that was generated in the Azure portal. 客户端密码在此流中用于 Web 应用场景,在其中客户端可以安全地存储客户端密码。Client secrets are used in this flow for Web App scenarios, where the client can securely store a client secret. 对于本机应用(公共客户端)场景,客户端密码不能安全地存储,因此不能在此流上使用。For Native App (public client) scenarios, client secrets cannot be securely stored, therefore not used on this flow. 如果使用客户端密码,请定期更改。If using a client secret, please change it on a periodic basis.
codecode Yes 在用户流的开头获取的授权代码。The authorization code that you acquired in the beginning of the user flow.
grant_typegrant_type Yes 授予类型,该类型必须是授权代码流的 authorization_codeThe type of grant, which must be authorization_code for the authorization code flow.
redirect_uriredirect_uri Yes 在其中收到授权代码的应用程序的 redirect_uri 参数。The redirect_uri parameter of the application where you received the authorization code.
scopescope No 范围的空格分隔列表。A space-separated list of scopes. openid 作用域表示允许使用 id_token 参数的形式使用户登录并获取有关用户的数据。The openid scope indicates a permission to sign in the user and get data about the user in the form of id_token parameters. 它可以用于为应用程序的后端 Web API 获取令牌,该令牌使用和客户端相同的应用程序 ID 表示。It can be used to get tokens to your application's own back-end web API, which is represented by the same application ID as the client. offline_access 范围表示应用程序需要使用刷新令牌来长期访问资源。The offline_access scope indicates that your application needs a refresh token for extended access to resources.

成功的令牌响应如下所示:A successful token response looks like:

{
    "not_before": "1442340812",
    "token_type": "Bearer",
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "scope": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
    "expires_in": "3600",
    "refresh_token": "AAQfQmvuDy8WtUv-sd0TBwWVQs1rC-Lfxa_NDkLqpg50Cxp5Dxj0VPF1mx2Z...",
}
参数Parameter 说明Description
not_beforenot_before epoch 时间中令牌被视为有效的时间。The time at which the token is considered valid, in epoch time.
token_typetoken_type 令牌类型值。The token type value. Bearer 是唯一支持的类型。Bearer is the only type that is supported.
access_tokenaccess_token 请求的已签名的 JWT 令牌。The signed JWT token that you requested.
scopescope 令牌的有效范围。The scopes for which the token is valid.
expires_inexpires_in 访问令牌有效的时间长度(以秒为单位)。The length of time that the access token is valid (in seconds).
refresh_tokenrefresh_token OAuth 2.0 刷新令牌。An OAuth 2.0 refresh token. 应用程序可以使用此令牌,在当前令牌过期之后获取其他令牌。The application can use this token to acquire additional tokens after the current token expires. 刷新令牌可用于延长保留资源访问权限的时间。Refresh tokens can be used to retain access to resources for extended periods of time. 必须在授权和令牌请求中使用范围 offline_access,才能接收刷新令牌。The scope offline_access must have been used in both the authorization and token requests in order to receive a refresh token.

错误响应如下所示:Error responses look like:

{
    "error": "access_denied",
    "error_description": "The user revoked access to the app.",
}
参数Parameter 说明Description
errorerror 一个代码,可用于对发生的错误类型进行分类。A code that can be used to classify types of errors that occur.
error_descriptionerror_description 帮助识别身份验证错误根本原因的消息。A message that can help identify the root cause of an authentication error.

使用令牌Use the token

现在你已成功获取访问令牌,可通过在 Authorization 标头中加入令牌的方式,在后端 Web API 请求中使用该令牌:Now that you've successfully acquired an access token, you can use the token in requests to your back-end web APIs by including it in the Authorization header:

GET /tasks
Host: mytaskwebapi.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...

刷新令牌Refresh the token

ID 令牌在短时间内即会过期。ID tokens expire in a short period of time. 在它们过期后,请刷新令牌以便能够继续访问资源。Refresh the tokens after they expire to continue being able to access resources. 可以通过向 /token 终结点提交另一个 POST 请求来刷新令牌。You can refresh a token by submitting another POST request to the /token endpoint. 此时,提供 refresh_token 参数而不是 code 参数:This time, provide the refresh_token parameter instead of the code parameter:

POST {tenant}.partner.onmschina.cn/{policy}/oauth2/v2.0/token HTTP/1.1
Host: {tenant}.b2clogin.cn
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=openid offline_access&refresh_token=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:wg:oauth:2.0:oob
参数Parameter 必须Required 说明Description
{tenant}{tenant} Yes Azure AD B2C 租户的名称Name of your Azure AD B2C tenant
{policy}{policy} Yes 用于获取原始刷新令牌的用户流。The user flow that was used to acquire the original refresh token. 无法在此请求中使用不同的用户流。You can't use a different user flow in this request. 将此参数添加到查询字符串中,而不是添加到 POST 正文中。Add this parameter to the query string, not to the POST body.
client_idclient_id Yes Azure 门户分配给应用程序的应用程序 ID。The application ID that the Azure portal assigned to your application.
client_secretclient_secret 是,在 Web 应用中Yes, in Web Apps Azure 门户中生成的应用程序机密。The application secret that was generated in the Azure portal. 客户端密码在此流中用于 Web 应用场景,在其中客户端可以安全地存储客户端密码。Client secrets are used in this flow for Web App scenarios, where the client can securely store a client secret. 对于本机应用(公共客户端)场景,客户端密码不能安全地存储,因此不能用于此调用。For Native App (public client) scenarios, client secrets cannot be securely stored, therefore not used on this call. 如果使用客户端密码,请定期更改。If using a client secret, please change it on a periodic basis.
grant_typegrant_type Yes 授予类型,必须是此授权代码流部分的刷新令牌。The type of grant, which must be a refresh token for this part of the authorization code flow.
refresh_tokenrefresh_token Yes 在流的第二部分获取的原始刷新令牌。The original refresh token that was acquired in the second part of the flow. 必须在授权和令牌请求中使用范围 offline_access,才能接收刷新令牌。The offline_access scope must be used in both the authorization and token requests in order to receive a refresh token.
redirect_uriredirect_uri No 在其中收到授权代码的应用程序的 redirect_uri 参数。The redirect_uri parameter of the application where you received the authorization code.
scopescope No 范围的空格分隔列表。A space-separated list of scopes. openid 作用域表示允许使用 ID 令牌的形式使用户登录并获取有关用户的数据。The openid scope indicates a permission to sign in the user and get data about the user in the form of ID tokens. 它可以用于向应用程序的后端 Web API 发送令牌,该令牌使用和客户端相同的应用程序 ID 表示。It can be used to send tokens to your application's own back-end web API, which is represented by the same application ID as the client. offline_access 范围表示应用程序需要使用刷新令牌来长期访问资源。The offline_access scope indicates that your application needs a refresh token for extended access to resources.

成功的令牌响应如下所示:A successful token response looks like:

{
    "not_before": "1442340812",
    "token_type": "Bearer",
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "scope": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
    "expires_in": "3600",
    "refresh_token": "AAQfQmvuDy8WtUv-sd0TBwWVQs1rC-Lfxa_NDkLqpg50Cxp5Dxj0VPF1mx2Z...",
}
参数Parameter 说明Description
not_beforenot_before epoch 时间中令牌被视为有效的时间。The time at which the token is considered valid, in epoch time.
token_typetoken_type 令牌类型值。The token type value. Bearer 是唯一支持的类型。Bearer is the only type that is supported.
access_tokenaccess_token 请求的已签名 JWT 令牌。The signed JWT token that was requested.
scopescope 令牌的有效范围。The scope for which the token is valid.
expires_inexpires_in 访问令牌有效的时间长度(以秒为单位)。The length of time that the access token is valid (in seconds).
refresh_tokenrefresh_token OAuth 2.0 刷新令牌。An OAuth 2.0 refresh token. 应用程序可以使用此令牌,在当前令牌过期之后获取其他令牌。The application can use this token to acquire additional tokens after the current token expires. 刷新令牌可用于延长保留资源访问权限的时间。Refresh tokens can be used to retain access to resources for extended periods of time.

错误响应如下所示:Error responses look like:

{
    "error": "access_denied",
    "error_description": "The user revoked access to the app.",
}
参数Parameter 说明Description
errorerror 一个代码,可用于对发生的错误类型进行分类。A code that can be used to classify types of errors that occur.
error_descriptionerror_description 帮助识别身份验证错误根本原因的消息。A message that can help identify the root cause of an authentication error.

发送注销请求Send a sign-out request

如果想要从应用程序中注销用户,只是清除应用程序的 Cookie 或者结束与用户的会话是不够的。When you want to sign the user out of the application, it isn't enough to clear the application's cookies or otherwise end the session with the user. 需将用户重定向到 Azure AD B2C 进行注销。如果没有这么做,那么用户可能可以在应用程序中重新进行身份验证,且无需再次输入其凭据。Redirect the user to Azure AD B2C to sign out. If you fail to do so, the user might be able to reauthenticate to your application without entering their credentials again. 有关详细信息,请参阅 Azure AD B2C 会话For more information, see Azure AD B2C session.

若要将用户注销,请将用户重定向到前面所述的 OpenID Connect 元数据文档中列出的 end_session 终结点:To sign out the user, redirect the user to the end_session endpoint that is listed in the OpenID Connect metadata document described earlier:

GET https://{tenant}.b2clogin.cn/{tenant}.partner.onmschina.cn/{policy}/oauth2/v2.0/logout?post_logout_redirect_uri=https%3A%2F%2Fjwt.ms%2F
参数Parameter 必须Required 说明Description
{tenant}{tenant} Yes Azure AD B2C 租户的名称Name of your Azure AD B2C tenant
{policy}{policy} Yes 想要用于从应用程序中注销用户的用户流。The user flow that you want to use to sign the user out of your application.
id_token_hintid_token_hint No 以前颁发的 ID 令牌,该令牌将作为有关最终用户当前与客户端建立的身份验证会话的提示传递给注销终结点。A previously issued ID token to pass to the logout endpoint as a hint about the end user's current authenticated session with the client. id_token_hint 确保 post_logout_redirect_uri 是 Azure AD B2C 应用程序设置中的已注册回复 URL。The id_token_hint ensures that the post_logout_redirect_uri is a registered reply URL in your Azure AD B2C application settings.
client_idclient_id 否*No* Azure 门户分配给应用程序的应用程序 ID。The application ID that the Azure portal assigned to your application.

*使用 Application 隔离 SSO 配置并且注销请求中的所需 ID 令牌设置为 No 时,这是必需的。*This is required when using Application isolation SSO configuration and Require ID Token in logout request is set to No.
post_logout_redirect_uripost_logout_redirect_uri No 用户在成功注销后应重定向到的 URL。如果未包含此参数,Azure AD B2C 会向用户显示一条常规消息。The URL that the user should be redirected to after successful sign out. If it isn't included, Azure AD B2C shows the user a generic message. 除非提供 id_token_hint,否则不应在 Azure AD B2C 应用程序设置中将此 URL 注册为回复 URL。Unless you provide an id_token_hint, you should not register this URL as a reply URL in your Azure AD B2C application settings.
statestate No 如果请求中包含 state 参数,响应中就应该出现相同的值。If a state parameter is included in the request, the same value should appear in the response. 应用程序需验证请求和响应中的 state 值是否相同。The application should verify that the state values in the request and response are identical.

保护注销重定向Secure your logout redirect

注销后,用户将重定向到 post_logout_redirect_uri 参数中指定的 URI,而不管为应用程序指定的回复 URL 为何。After logout, the user is redirected to the URI specified in the post_logout_redirect_uri parameter, regardless of the reply URLs that have been specified for the application. 但是,如果传递了有效的 id_token_hint,则在执行重定向之前,Azure AD B2C 将验证 post_logout_redirect_uri 的值是否与应用程序的某个已配置重定向 URI 相匹配。However, if a valid id_token_hint is passed, Azure AD B2C verifies that the value of post_logout_redirect_uri matches one of the application's configured redirect URIs before performing the redirect. 如果没有为应用程序配置匹配的回复 URL,则会显示一条错误消息,而用户不会重定向。If no matching reply URL was configured for the application, an error message is displayed and the user is not redirected.