使用 OpenID Connect 和 Azure Active Directory 来授权访问 Web 应用程序Authorize access to web applications using OpenID Connect and Azure Active Directory

OpenID Connect 是基于 OAuth 2.0 协议构建的简单标识层。OpenID Connect is a simple identity layer built on top of the OAuth 2.0 protocol. OAuth 2.0 定义了一些机制用于获取和使用访问令牌来访问受保护资源,但未定义用于提供标识信息的标准方法。OAuth 2.0 defines mechanisms to obtain and use access tokens to access protected resources, but they do not define standard methods to provide identity information. OpenID Connect 实现身份验证,作为对 OAuth 2.0 授权过程的扩展。OpenID Connect implements authentication as an extension to the OAuth 2.0 authorization process. 它以 id_token 的形式提供有关最终用户的信息,可验证用户的标识,并提供有关用户的基本配置文件信息。It provides information about the end user in the form of an id_token that verifies the identity of the user and provides basic profile information about the user.

如果要构建的 Web 应用程序托管在服务器中并通过浏览器访问,我们建议使用 OpenID Connect。OpenID Connect is our recommendation if you are building a web application that is hosted on a server and accessed via a browser.

将应用程序注册到 AD 租户Register your application with your AD tenant

首先,需要将应用程序注册到 Azure Active Directory (Azure AD) 租户。First, you need to register your application with your Azure Active Directory (Azure AD) tenant. 这会为应用程序分配一个应用程序 ID,并且使该应用程序可以接收令牌。This will give you an Application ID for your application, as well as enable it to receive tokens.

  • 登录到 Azure 门户Sign in to the Azure portal.
  • 通过以下方式选择 Azure AD 租户:在页面右上角单击你的帐户,单击“切换目录”导航,然后选择合适的租户。Choose your Azure AD tenant by clicking on your account in the top right corner of the page, followed by clicking on the Switch Directory navigation and then select the appropriate tenant.
    • 如果你的帐户下只有一个 Azure AD 租户,或者已选择了合适的 Azure AD 租户,请跳过此步骤。Skip this step, if you've only one Azure AD tenant under your account or if you've already selected the appropriate Azure AD tenant.
  • 在左侧的导航窗格中,单击“Azure Active Directory”。In the left hand navigation pane, click on Azure Active Directory.
  • 单击“应用注册”并单击“新建应用程序注册”。Click on App Registrations and click on New application registration.
  • 根据提示创建新的应用程序。Follow the prompts and create a new application. 本教程简要介绍了 Web 应用程序和本机应用程序的操作步骤,如果想要查看 Web 应用程序或本机应用程序的具体示例,请参阅快速入门It doesn't matter if it is a web application or a native application for this tutorial, but if you'd like specific examples for web applications or native applications, check out our quickstarts.
    • 对于 Web 应用程序,请在用户登录页面(如 http://localhost:12345)提供“登录 URL”,即应用的基 URL。For Web Applications, provide the Sign-On URL, which is the base URL of your app, where users can sign in e.g http://localhost:12345.
    • 对于本机应用程序,请提供“重定向 URI”,Azure AD 将用其返回令牌响应。For Native Applications provide a Redirect URI, which Azure AD will use to return token responses. 输入特定于应用程序的值,例如 http://MyFirstAADAppEnter a value specific to your application, .e.g http://MyFirstAADApp
  • 完成注册后,Azure AD 将为应用程序分配一个唯一的客户端标识符,即应用程序 ID。Once you've completed registration, Azure AD will assign your application a unique client identifier, the Application ID. 在后面的部分中会用到此值,因此,请从应用程序页复制此值。You need this value in the next sections, so copy it from the application page.
  • 若要在 Azure 门户中找到应用程序,请依次单击“应用注册”、“查看所有应用程序”。To find your application in the Azure portal, click App registrations, and then click View all applications.

使用 OpenID Connect 的身份验证流Authentication flow using OpenID Connect

最基本的登录流包含以下步骤 - 下面详细描述了每个步骤。The most basic sign-in flow contains the following steps - each of them is described in detail below.

OpenID Connect 身份验证流

OpenID Connect 元数据文档OpenID Connect metadata document

OpenID Connect 描述了元数据文档,该文档包含了应用执行登录所需的大部分信息。OpenID Connect describes a metadata document that contains most of the information required for an app to perform sign-in. 这包括要使用的 URL 和服务的公共签名密钥的位置等信息。This includes information such as the URLs to use and the location of the service's public signing keys. OpenID Connect 元数据文档可以在以下位置找到:The OpenID Connect metadata document can be found at:

https://login.partner.microsoftonline.cn/{tenant}/.well-known/openid-configuration

元数据是简单的 JavaScript 对象表示法 (JSON) 文档。The metadata is a simple JavaScript Object Notation (JSON) document. 有关示例,请参阅下面的代码段。See the following snippet for an example. OpenID Connect 规范中完整介绍了该代码片段的内容。The snippet's contents are fully described in the OpenID Connect specification. 请注意,提供租户 ID 而不是用 common 代替上面的 {tenant} 将导致在 JSON 对象中返回特定于租户的 URI。Note that providing a tenant ID rather than common in place of {tenant} above will result in tenant-specific URIs in the JSON object returned.

{
    "authorization_endpoint": "https://login.partner.microsoftonline.cn/{tenant}/oauth2/authorize",
    "token_endpoint": "https://login.partner.microsoftonline.cn/{tenant}/oauth2/token",
    "token_endpoint_auth_methods_supported":
    [
        "client_secret_post",
        "private_key_jwt",
        "client_secret_basic"
    ],
    "jwks_uri": "https://login.partner.microsoftonline.cn/common/discovery/keys"
    "userinfo_endpoint":"https://login.partner.microsoftonline.cn/{tenant}/openid/userinfo",
    ...
}

如果应用因使用声明映射功能而具有自定义签名密钥,则必须追加包含应用 ID 的 appid 查询参数,以获取指向应用的签名密钥信息的 jwks_uriIf your app has custom signing keys as a result of using the claims-mapping feature, you must append an appid query parameter containing the app ID in order to get a jwks_uri pointing to your app's signing key information. 例如:https://login.partner.microsoftonline.cn/{tenant}/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e 包含 https://login.partner.microsoftonline.cn/{tenant}/discovery/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391ejwks_uriFor example: https://login.partner.microsoftonline.cn/{tenant}/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e contains a jwks_uri of https://login.partner.microsoftonline.cn/{tenant}/discovery/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391e.

发送登录请求Send the sign-in request

当 Web 应用程序需要对用户进行身份验证时,必须将用户定向到 /authorize 终结点。When your web application needs to authenticate the user, it must direct the user to the /authorize endpoint. 此请求类似于 OAuth 2.0 授权代码流的第一个阶段,不过有几个重要的区别:This request is similar to the first leg of the OAuth 2.0 Authorization Code Flow, with a few important distinctions:

  • 该请求必须在 scope 参数中包含范围 openidThe request must include the scope openid in the scope parameter.
  • response_type 参数必须包含 id_tokenThe response_type parameter must include id_token.
  • 请求必须在 nonceThe request must include the nonce parameter.

下面是一个示例请求:So a sample request would look like this:

// Line breaks for legibility only

GET https://login.partner.microsoftonline.cn/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=id_token
&redirect_uri=http%3A%2F%2Flocalhost%3a12345
&response_mode=form_post
&scope=openid
&state=12345
&nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
参数Parameter 说明Description
tenanttenant 必填required 请求路径中的 {tenant} 值可用于控制哪些用户可以登录应用程序。The {tenant} value in the path of the request can be used to control who can sign into the application. 允许值为租户标识符,例如独立于租户令牌的 8eaef023-2b34-4da1-9baa-8bc8c9d6a490contoso.partner.onmschina.cncommonThe allowed values are tenant identifiers, for example, 8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or contoso.partner.onmschina.cn or common for tenant-independent tokens
client_idclient_id 必填required 将应用注册到 Azure AD 时,分配给应用的应用程序 ID。The Application ID assigned to your app when you registered it with Azure AD. 可以在 Azure 门户中找到该值。You can find this in the Azure portal. 依次单击“Azure Active Directory” 和“应用注册” ,选择应用程序并在应用程序页上找到应用程序 ID。Click Azure Active Directory, click App Registrations, choose the application and locate the Application ID on the application page.
response_typeresponse_type 必填required 必须包含 OpenID Connect 登录的 id_tokenMust include id_token for OpenID Connect sign-in. 还可以包含其他 response_type,例如 codetokenIt may also include other response_types, such as code or token.
scopescope 建议recommended OpenID Connect 规范要求范围 openid,该范围在许可 UI 中会转换为“将你登录”权限。The OpenID Connect specification requires the scope openid, which translates to the "Sign you in" permission in the consent UI. 在 v1.0 终结点上,此范围和其他 OIDC 范围会被忽略,但对符合标准的客户端而言仍是最佳做法。This and other OIDC scopes are ignored on the v1.0 endpoint, but is still a best practice for standards-compliant clients.
noncenonce 必填required 由应用生成且包含在请求中的值,以声明方式包含在生成的 id_token 中。A value included in the request, generated by the app, that is included in the resulting id_token as a claim. 应用程序接着便可确认此值,以减少令牌重新执行攻击。The app can then verify this value to mitigate token replay attacks. 此值通常是随机的唯一字符串或 GUID,可用以识别请求的来源。The value is typically a randomized, unique string or GUID that can be used to identify the origin of the request.
redirect_uriredirect_uri 建议recommended 应用的 redirect_uri,应用可向其发送及从其接收身份验证响应。The redirect_uri of your app, where authentication responses can be sent and received by your app. 它必须完全符合在门户中注册的其中一个 redirect_uris,否则必须是编码的 url。It must exactly match one of the redirect_uris you registered in the portal, except it must be url encoded. 如果缺失,则会将用户代理随机发送回某个为应用注册的重定向 URI。If missing, the user agent will be sent back to one of the redirect URIs registered for the app, at random. 最大长度为 255 字节The maximum length is 255 bytes
response_moderesponse_mode 可选optional 指定将生成的 authorization_code 送回到应用程序所应使用的方法。Specifies the method that should be used to send the resulting authorization_code back to your app. HTTP 窗体发布 支持的值为 form_post,URL 片段 支持的值为 fragmentSupported values are form_post for HTTP form post and fragment for URL fragment. 对于 Web 应用程序,建议使用 response_mode=form_post ,确保以最安全的方式将令牌传输到应用程序。For web applications, we recommend using response_mode=form_post to ensure the most secure transfer of tokens to your application. 包含 id_token 的任何流的默认值为 fragmentThe default for any flow including an id_token is fragment.
statestate 建议recommended 随令牌响应返回的请求中所包含的值。A value included in the request that is returned in the token response. 可以是想要的任何内容的字符串。It can be a string of any content that you wish. 随机生成的唯一值通常用于防止跨站点请求伪造攻击A randomly generated unique value is typically used for preventing cross-site request forgery attacks. 该 state 也用于在身份验证请求出现之前,于应用中编码用户的状态信息,例如之前所在的网页或视图。The state is also used to encode information about the user's state in the app before the authentication request occurred, such as the page or view they were on.
promptprompt 可选optional 表示需要的用户交互类型。Indicates the type of user interaction that is required. 当前仅有的有效值为“login”、“none”和“consent”。Currently, the only valid values are 'login', 'none', and 'consent'. prompt=login 强制用户在该请求上输入其凭据,从而使单一登录无效。prompt=login forces the user to enter their credentials on that request, negating single-sign on. prompt=none 完全相反,它会确保无论如何都不向用户显示任何交互提示。prompt=none is the opposite - it ensures that the user is not presented with any interactive prompt whatsoever. 如果请求无法通过单一登录静默完成,则终结点返回一个错误。If the request cannot be completed silently via single-sign on, the endpoint returns an error. prompt=consent 在用户登录后触发 OAuth 许可对话框,要求用户向应用授予权限。prompt=consent triggers the OAuth consent dialog after the user signs in, asking the user to grant permissions to the app.
login_hintlogin_hint 可选optional 如果事先知道用户名,可用于预先填充用户登录页的用户名/电子邮件地址字段。Can be used to pre-fill the username/email address field of the sign-in page for the user, if you know their username ahead of time. 通常,应用在重新身份验证期间使用此参数,并且已经使用 preferred_username 声明从前次登录提取用户名。Often apps use this parameter during reauthentication, having already extracted the username from a previous sign-in using the preferred_username claim.

此时,系统会要求用户输入凭据并完成身份验证。At this point, the user is asked to enter their credentials and complete the authentication.

示例响应Sample response

在用户进行身份验证后发送到登录请求中指定的 redirect_uri 的示例响应可能如下所示:A sample response, sent to the redirect_uri specified in the sign-in request after the user has authenticated, could look like this:

POST / HTTP/1.1
Host: localhost:12345
Content-Type: application/x-www-form-urlencoded

id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345
参数Parameter 说明Description
id_tokenid_token 应用请求的 id_tokenThe id_token that the app requested. 可以使用 id_token 验证用户的标识,并以用户身份开始会话。You can use the id_token to verify the user's identity and begin a session with the user.
statestate 同时随令牌响应返回的请求中所包含的值。A value included in the request that is also returned in the token response. 随机生成的唯一值通常用于 防止跨站点请求伪造攻击A randomly generated unique value is typically used for preventing cross-site request forgery attacks. 该 state 也用于在身份验证请求出现之前,于应用中编码用户的状态信息,例如之前所在的网页或视图。The state is also used to encode information about the user's state in the app before the authentication request occurred, such as the page or view they were on.

错误响应Error response

错误响应可能也发送到 redirect_uri ,让应用可以适当地处理:Error responses may also be sent to the redirect_uri so the app can handle them appropriately:

POST / HTTP/1.1
Host: localhost:12345
Content-Type: application/x-www-form-urlencoded

error=access_denied&error_description=the+user+canceled+the+authentication
参数Parameter 说明Description
errorerror 用于分类发生的错误类型与响应错误的错误码字符串。An error code string that can be used to classify types of errors that occur, and can be used to react to errors.
error_descriptionerror_description 帮助开发人员识别身份验证错误根本原因的特定错误消息。A specific error message that can help a developer identify the root cause of an authentication error.

授权终结点错误的错误代码Error codes for authorization endpoint errors

下表描述了可在错误响应的 error 参数中返回的各个错误代码。The following table describes the various error codes that can be returned in the error parameter of the error response.

错误代码Error Code 说明Description 客户端操作Client Action
invalid_requestinvalid_request 协议错误,例如,缺少必需的参数。Protocol error, such as a missing required parameter. 修复并重新提交请求。Fix and resubmit the request. 这通常是在初始测试期间捕获的开发错误。This is a development error, and is typically caught during initial testing.
unauthorized_clientunauthorized_client 不允许客户端应用程序请求授权代码。The client application is not permitted to request an authorization code. 客户端应用程序未注册到 Azure AD 中或者未添加到用户的 Azure AD 租户时,通常会出现这种情况。This usually occurs when the client application is not registered in Azure AD or is not added to the user's Azure AD tenant. 应用程序可以提示用户,并说明如何安装应用程序并将其添加到 Azure AD。The application can prompt the user with instruction for installing the application and adding it to Azure AD.
access_deniedaccess_denied 资源所有者拒绝了许可Resource owner denied consent 客户端应用程序可以通知用户除非用户许可,否则无法继续。The client application can notify the user that it cannot proceed unless the user consents.
unsupported_response_typeunsupported_response_type 授权服务器不支持请求中的响应类型。The authorization server does not support the response type in the request. 修复并重新提交请求。Fix and resubmit the request. 这通常是在初始测试期间捕获的开发错误。This is a development error, and is typically caught during initial testing.
server_errorserver_error 服务器遇到意外的错误。The server encountered an unexpected error. 重试请求。Retry the request. 这些错误可能是临时状况导致的。These errors can result from temporary conditions. 客户端应用程序可向用户说明,其响应由于临时错误而延迟。The client application might explain to the user that its response is delayed due to a temporary error.
temporarily_unavailabletemporarily_unavailable 服务器暂时繁忙,无法处理请求。The server is temporarily too busy to handle the request. 重试请求。Retry the request. 客户端应用程序可向用户说明,其响应由于临时状况而延迟。The client application might explain to the user that its response is delayed due to a temporary condition.
invalid_resourceinvalid_resource 目标资源无效,原因是它不存在,Azure AD 找不到它,或者未正确配置。The target resource is invalid because it does not exist, Azure AD cannot find it, or it is not correctly configured. 这表示未在租户中配置该资源(如果存在)。This indicates the resource, if it exists, has not been configured in the tenant. 应用程序可以提示用户,并说明如何安装应用程序并将其添加到 Azure AD。The application can prompt the user with instruction for installing the application and adding it to Azure AD.

验证 id_tokenValidate the id_token

仅接收 id_token 不足以对用户进行身份验证,必须验证签名,并按照应用的要求验证 id_token 中的声明。Just receiving an id_token is not sufficient to authenticate the user; you must validate the signature and verify the claims in the id_token per your app's requirements. Azure AD 终结点使用 JSON Web 令牌 (JWT) 和公钥加密对令牌进行签名并验证其是否有效。The Azure AD endpoint uses JSON Web Tokens (JWTs) and public key cryptography to sign tokens and verify that they are valid.

可以选择验证客户端代码中的 id_token,但常见的做法是将 id_token 发送到后端服务器,并在那里执行验证。You can choose to validate the id_token in client code, but a common practice is to send the id_token to a backend server and perform the validation there.

可能还希望根据自己的方案验证其他声明。You may also wish to validate additional claims depending on your scenario. 一些常见的验证包括:Some common validations include:

  • 确保用户/组织已注册应用。Ensuring the user/organization has signed up for the app.
  • 使用 widsroles 声明,确保用户拥有正确的授权/权限。Ensuring the user has proper authorization/privileges using the wids or roles claims.
  • 确保身份验证具有一定的强度,例如多重身份验证。Ensuring a certain strength of authentication has occurred, such as multi-factor authentication.

验证 id_token 后,即可开始与用户的会话,并使用 id_token 中的声明来获取应用中的用户相关信息。Once you have validated the id_token, you can begin a session with the user and use the claims in the id_token to obtain information about the user in your app. 此信息可用于显示、记录和个性化等。有关 id_tokens 和声明的详细信息,请阅读 AAD id_tokensThis information can be used for display, records, personalization, etc. For more information about id_tokens and claims, read AAD id_tokens.

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

如果希望用户从应用中注销,仅仅是清除应用的 Cookie 或结束用户会话并不足够。When you wish to sign the user out of the app, it is not sufficient to clear your app's cookies or otherwise end the session with the user. 还必须将用户重定向到 end_session_endpoint 才能注销。如果不这样做,用户可能不需要再次输入凭据就能重新通过应用的身份验证,因为他们与 Azure AD 终结点之间仍然存在有效的单一登录会话。You must also redirect the user to the end_session_endpoint for sign-out. If you fail to do so, the user will be able to reauthenticate to your app without entering their credentials again, because they will have a valid single sign-on session with the Azure AD endpoint.

只需将用户重定向到 OpenID Connect 元数据文档中所列的 end_session_endpointYou can simply redirect the user to the end_session_endpoint listed in the OpenID Connect metadata document:

GET https://login.partner.microsoftonline.cn/common/oauth2/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F

参数Parameter 说明Description
post_logout_redirect_uripost_logout_redirect_uri 建议recommended 用户在成功注销后应重定向到的 URL。此 URL 必须与在应用注册门户中为应用程序注册的重定向 URI 之一匹配。The URL that the user should be redirected to after successful sign out. This URL must match one of the redirect URIs registered for your application in the app registration portal. 如果未包含 post_logout_redirect_uri ,系统会向用户显示一条常规消息。If post_logout_redirect_uri is not included, the user is shown a generic message.

单一登录Single sign-out

将用户重定向到 end_session_endpoint 时,Azure AD 将从浏览器中清除用户的会话。When you redirect the user to the end_session_endpoint, Azure AD clears the user's session from the browser. 但是,用户可能仍登录到其他使用 Azure AD 进行身份验证的应用程序。However, the user may still be signed in to other applications that use Azure AD for authentication. 要使这些应用程序能够同时注销用户,Azure AD 会将 HTTP GET 请求发送到用户当前登录到的所有应用程序的已注册 LogoutUrlTo enable those applications to sign the user out simultaneously, Azure AD sends an HTTP GET request to the registered LogoutUrl of all the applications that the user is currently signed in to. 应用程序必须通过清除任何标识用户的会话并返回 200 响应来响应此请求。Applications must respond to this request by clearing any session that identifies the user and returning a 200 response. 如果要在应用程序中支持单一注销,必须在应用程序代码中实现此类 LogoutUrlIf you wish to support single sign out in your application, you must implement such a LogoutUrl in your application's code. 可以从 Azure 门户设置 LogoutUrlYou can set the LogoutUrl from the Azure portal:

  1. 导航到 Azure 门户Navigate to the Azure portal.
  2. 通过单击页面右上角的帐户选择 Active Directory。Choose your Active Directory by clicking on your account in the top right corner of the page.
  3. 从左侧导航面板中,选择“Azure Active Directory” ,选择“应用注册” ,并选择应用程序。From the left hand navigation panel, choose Azure Active Directory, then choose App registrations and select your application.
  4. 单击“设置” 和“属性” ,并查找“注销 URL” 文本框。Click on Settings, then Properties and find the Logout URL text box.

令牌获取Token Acquisition

许多 Web 应用不仅需要将用户登录,而且还要代表该用户使用 OAuth 来访问 Web 服务。Many web apps need to not only sign the user in, but also access a web service on behalf of that user using OAuth. 此方案合并了用于对用户进行身份验证的 OpenID Connect,同时将获取 authorization_code,可用于通过 OAuth 授权代码流来获取 access_tokensThis scenario combines OpenID Connect for user authentication while simultaneously acquiring an authorization_code that can be used to get access_tokens using the OAuth Authorization Code Flow.

获取访问令牌Get Access Tokens

若要获取访问令牌,需要修改上述登录请求:To acquire access tokens, you need to modify the sign-in request from above:

// Line breaks for legibility only

GET https://login.partner.microsoftonline.cn/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e        // Your registered Application ID
&response_type=id_token+code
&redirect_uri=http%3A%2F%2Flocalhost%3a12345          // Your registered Redirect Uri, url encoded
&response_mode=form_post                              // `form_post' or 'fragment'
&scope=openid
&resource=https%3A%2F%2Fservice.contoso.com%2F        // The identifier of the protected resource (web API) that your application needs access to
&state=12345                                          // Any value, provided by your app
&nonce=678910                                         // Any value, provided by your app

通过在请求中包含权限范围并使用 response_type=code+id_tokenauthorize 终结点可确保用户已经同意 scope 查询参数中指示的权限,并且将授权代码返回到应用以交换访问令牌。By including permission scopes in the request and using response_type=code+id_token, the authorize endpoint ensures that the user has consented to the permissions indicated in the scope query parameter, and return your app an authorization code to exchange for an access token.

成功的响应Successful response

使用 response_mode=form_post 发送到 redirect_uri 的成功响应如下所示:A successful response, sent to the redirect_uri using response_mode=form_post, looks like:

POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded

id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&state=12345
参数Parameter 说明Description
id_tokenid_token 应用请求的 id_tokenThe id_token that the app requested. 可以使用 id_token 验证用户的标识,并以用户身份开始会话。You can use the id_token to verify the user's identity and begin a session with the user.
codecode 应用请求的 authorization_code。The authorization_code that the app requested. 应用程序可以使用授权代码请求目标资源的访问令牌。The app can use the authorization code to request an access token for the target resource. Authorization_codes 的生存期较短,通常在约 10 分钟后即过期。Authorization_codes are short lived, and typically expire after about 10 minutes.
statestate 如果请求中包含状态参数,响应中就应该出现相同的值。If a state parameter is included in the request, the same value should appear in the response. 应用应该验证请求和响应中的 state 值是否完全相同。The app should verify that the state values in the request and response are identical.

错误响应Error response

错误响应可能也发送到 redirect_uri ,让应用可以适当地处理:Error responses may also be sent to the redirect_uri so the app can handle them appropriately:

POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded

error=access_denied&error_description=the+user+canceled+the+authentication
参数Parameter 说明Description
errorerror 用于分类发生的错误类型与响应错误的错误码字符串。An error code string that can be used to classify types of errors that occur, and can be used to react to errors.
error_descriptionerror_description 帮助开发人员识别身份验证错误根本原因的特定错误消息。A specific error message that can help a developer identify the root cause of an authentication error.

有关可能的错误代码的描述及其建议的客户端操作,请参阅 授权终结点错误的错误代码For a description of the possible error codes and their recommended client action, see Error codes for authorization endpoint errors.

获取授权 codeid_token 之后,可以将用户登录,并代表他们获取访问令牌Once you've gotten an authorization code and an id_token, you can sign the user in and get access tokens on their behalf. 要将用户登录,必须确切地按上面所述验证 id_tokenTo sign the user in, you must validate the id_token exactly as described above. 若要获取访问令牌,可以遵循 OAuth 代码流文档的“使用授权代码请求访问令牌”部分中所述的步骤。To get access tokens, you can follow the steps described in the "Use the authorization code to request an access token" section of our OAuth code flow documentation.

后续步骤Next steps