Microsoft 标识平台和 OpenID Connect 协议Microsoft identity platform and OpenID Connect protocol

OpenID Connect 是构建在 OAuth 2.0 基础之上的身份验证协议,可用于将用户安全登录到 Web 应用程序。OpenID Connect is an authentication protocol built on OAuth 2.0 that you can use to securely sign in a user to a web application. 使用 Microsoft 标识平台终结点的 OpenID Connect 实现时,可将登录功能和 API 访问权限添加到基于 Web 的应用中。When you use the Microsoft identity platform endpoint's implementation of OpenID Connect, you can add sign-in and API access to your web-based apps. 本文介绍如何独立于语言执行此操作,并介绍如何在不使用任何 Microsoft 开源库的情况下发送和接收 HTTP 消息。This article shows how to do this independent of language and describes how to send and receive HTTP messages without using any Microsoft open-source libraries.

Note

Microsoft 标识平台终结点并非支持所有 Azure Active Directory (Azure AD) 方案和功能。The Microsoft identity platform endpoint does not support all Azure Active Directory (Azure AD) scenarios and features. 若要确定是否应使用 Microsoft 标识平台终结点,请阅读 Microsoft 标识平台限制To determine whether you should use the Microsoft identity platform endpoint, read about Microsoft identity platform limitations.

OpenID Connect 扩展了 OAuth 2.0 授权协议,使其可用作身份验证协议,这样一来,用户可使用 OAuth 执行单一登录。OpenID Connect extends the OAuth 2.0 authorization protocol to use as an authentication protocol, so that you can do single sign-on using OAuth. OpenID Connect 引入了 ID 令牌的概念,这是一种安全令牌,可让客户端验证用户的标识。OpenID Connect introduces the concept of an ID token, which is a security token that allows the client to verify the identity of the user. ID 令牌还可获取有关用户的基本配置文件信息。The ID token also gets basic profile information about the user. 由于 OpenID Connect 扩展了 OAuth 2.0,因此应用可安全获取访问令牌,访问令牌可用于访问授权服务器保护的资源。 Because OpenID Connect extends OAuth 2.0, apps can securely acquire access tokens, which can be used to access resources that are secured by an authorization server. Microsoft 标识平台终结点还允许注册到 Azure AD 的第三方应用颁发受保护资源(例如 Web API)的访问令牌。The Microsoft identity platform endpoint also allows third-party apps that are registered with Azure AD to issue access tokens for secured resources such as web APIs. 有关如何设置应用程序以颁发访问令牌的详细信息,请参阅如何向 Microsoft 标识平台终结点注册应用For more information about how to set up an application to issue access tokens, see How to register an app with the Microsoft identity platform endpoint. 如果要构建在服务器上托管并通过浏览器访问的 Web 应用程序,建议使用 OpenID Connect。We recommend that you use OpenID Connect if you are building a web application that is hosted on a server and accessed via a browser.

协议图:登录Protocol diagram: Sign-in

最基本的登录流包含下图中所示的步骤。The most basic sign-in flow has the steps shown in the next diagram. 本文将详细介绍每个步骤。Each step is described in detail in this article.

OpenID Connect 协议:登录

提取 OpenID Connect 元数据文档Fetch the OpenID Connect metadata document

OpenID Connect 描述了元数据文档,该文档包含了应用执行登录所需的大部分信息。OpenID Connect describes a metadata document that contains most of the information required for an app to do sign-in. 这些信息包括要使用的 URL 以及服务公共签名密钥的位置。This includes information such as the URLs to use and the location of the service's public signing keys. 对于 Microsoft 标识平台终结点,应使用的 OpenID Connect 的元数据文档为:For the Microsoft identity platform endpoint, this is the OpenID Connect metadata document you should use:

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

{tenant} 可取以下四个值之一:The {tenant} can take one of four values:

Value 说明Description
common 在 Azure AD 中具有工作或学校帐户的用户可以登录到应用程序。Users with a work or school account from Azure AD can sign in to the application.
organizations 只有在 Azure AD 中具有工作或学校帐户的用户才能登录到应用程序。Only users with work or school accounts from Azure AD can sign in to the application.
8eaef023-2b34-4da1-9baa-8bc8c9d6a490contoso.partner.onmschina.cn8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or contoso.partner.onmschina.cn 只有来自特定 Azure AD 租户的用户(无论他们是否是具有工作或学校帐户的目录中的成员)才能登录到应用程序。Only users from a specific Azure AD tenant (whether they are members in the directory with a work or school account) can sign in to the application. 可以使用 Azure AD 租户的友好域名或租户的 GUID 标识符。Either the friendly domain name of the Azure AD tenant or the tenant's GUID identifier can be used. 也可以使用使用者租户 9188040d-6c67-4c5b-b112-36a304b66dad 来取代 consumers 租户。You can also use the consumer tenant, 9188040d-6c67-4c5b-b112-36a304b66dad, in place of the consumers tenant.

元数据是简单的 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.

{
  "authorization_endpoint": "https:\/\/login.partner.microsoftonline.cn\/{tenant}\/oauth2\/v2.0\/authorize",
  "token_endpoint": "https:\/\/login.partner.microsoftonline.cn\/{tenant}\/oauth2\/v2.0\/token",
  "token_endpoint_auth_methods_supported": [
    "client_secret_post",
    "private_key_jwt"
  ],
  "jwks_uri": "https:\/\/login.partner.microsoftonline.cn\/{tenant}\/discovery\/v2.0\/keys",

  ...

}

如果应用因使用声明映射功能而具有自定义签名密钥,则必须追加包含应用 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}/v2.0/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e 包含 https://login.partner.microsoftonline.cn/{tenant}/discovery/v2.0/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391ejwks_uriFor example: https://login.partner.microsoftonline.cn/{tenant}/v2.0/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e contains a jwks_uri of https://login.partner.microsoftonline.cn/{tenant}/discovery/v2.0/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391e.

通常,使用此元数据文档来配置 OpenID Connect 库或 SDK;该库使用元数据来完成其工作。Typically, you would use this metadata document to configure an OpenID Connect library or SDK; the library would use the metadata to do its work. 但是,如果不使用预生成的 OpenID Connect 库,则可以按照本文剩余部分的步骤来使用 Microsoft 标识平台终结点执行 Web 应用中的登录。However, if you're not using a pre-built OpenID Connect library, you can follow the steps in the remainder of this article to do sign-in in a web app by using the Microsoft identity platform endpoint.

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

当 Web 应用需要对用户进行身份验证时,可以将用户定向到 /authorize 终结点。When your web app needs to authenticate the user, it can 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 these important distinctions:

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

Important

若要从 /authorization 终结点成功请求 ID 令牌,注册门户中的应用注册必须在“身份验证”选项卡中启用 id_token 的隐式授予(将应用程序清单中的 oauth2AllowIdTokenImplicitFlow 标志设置为 true)。In order to successfully request an ID token from the /authorization endpoint, the app registration in the registration portal must have the implicit grant of id_tokens enabled in the Authentication tab (which sets the oauth2AllowIdTokenImplicitFlow flag in the application manifest to true). 如果未启用,将返回 unsupported_response 错误:“为输入参数 'response_type' 提供的值不允许用于此客户端。If it isn't enabled, an unsupported_response error will be returned: "The provided value for the input parameter 'response_type' isn't allowed for this client. 预期值为“code””Expected value is 'code'"

例如:For example:

// Line breaks are for legibility only.

GET https://login.partner.microsoftonline.cn/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=id_token
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=form_post
&scope=openid
&state=12345
&nonce=678910

Tip

单击以下链接执行此请求!Click the following link to execute this request. 登录后,浏览器将重定向到 https://localhost/myapp/,且地址栏中有一个 ID 令牌。After you sign in, your browser will be redirected to https://localhost/myapp/, with an ID token in the address bar. 请注意,此请求使用 response_mode=fragment(仅用于演示)。Note that this request uses response_mode=fragment (for demonstration purposes only). 建议使用 response_mode=form_postWe recommend that you use response_mode=form_post. https://login.partner.microsoftonline.cn/common/oauth2/v2.0/authorize...https://login.partner.microsoftonline.cn/common/oauth2/v2.0/authorize...

参数Parameter 条件Condition 说明Description
tenant 必需Required 可以在请求路径中使用 {tenant} 值来控制谁可以登录到应用程序。You can use the {tenant} value in the path of the request to control who can sign in to the application. 可以使用的值包括 commonorganizationsconsumers 和租户标识符。The allowed values are common, organizations, consumers, and tenant identifiers. 有关详细信息,请参见协议基础知识For more information, see protocol basics.
client_id 必需Required Azure 门户 - 应用注册体验分配给应用的应用程序(客户端)IDThe Application (client) ID that the Azure portal - App registrations experience assigned to your app.
response_type 必需Required 必须包含 OpenID Connect 登录的 id_tokenMust include id_token for OpenID Connect sign-in. 还可能包含其他 response_type 值,例如 codeIt might also include other response_type values, such as code.
redirect_uri 建议Recommended 应用的重定向 URI,应用可在其中发送和接收身份验证响应。The redirect URI of your app, where authentication responses can be sent and received by your app. 必须完全符合在门户中注册的重定向 URI 之一,否则必须是编码的 URL。It must exactly match one of the redirect URIs you registered in the portal, except that it must be URL encoded. 如果不存在该 URL,终结点将随机选取一个已注册的 redirect_uri,以将用户发回到其中。If not present, the endpoint will pick one registered redirect_uri at random to send the user back to.
scope 必需Required 范围的空格分隔列表。A space-separated list of scopes. 对于 OpenID Connect,它必须包含范围 openid,该范围在同意 UI 中会转换为“将你登录”权限。For OpenID Connect, it must include the scope openid, which translates to the "Sign you in" permission in the consent UI. 也可以在此请求中包含其他范围来请求许可。You might also include other scopes in this request for requesting consent.
nonce 必需Required 由应用程序生成且包含在请求中的值,以声明方式包含在生成的 id_token 值中。A value included in the request, generated by the app, that will be included in the resulting id_token value as a claim. 应用可以验证此值,以缓解令牌重放攻击。The app can verify this value to mitigate token replay attacks. 该值通常是随机化的唯一字符串,可用于标识请求的来源。The value typically is a randomized, unique string that can be used to identify the origin of the request.
response_mode 建议Recommended 指定将生成的授权代码发回给应用时应该使用的方法。Specifies the method that should be used to send the resulting authorization code back to your app. 可以是 form_postfragmentCan be form_post or 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.
state 建议Recommended 同样随令牌响应返回的请求中所包含的值。A value included in the request that also will be returned in the token response. 可以是所需的任何内容的字符串。It can be a string of any content you want. 随机生成的唯一值通常用于 防范跨站点请求伪造攻击A randomly generated unique value typically is used to prevent cross-site request forgery attacks. 该状态还用于在身份验证请求出现之前,在应用中编码用户的状态信息,例如用户过去所在的页面或视图。The state also is used to encode information about the user's state in the app before the authentication request occurred, such as the page or view the user was on.
prompt 可选Optional 表示需要的用户交互类型。Indicates the type of user interaction that is required. 目前仅有的有效值为 loginnoneconsentThe only valid values at this time are login, none, and consent. prompt=login 声明强制用户在该请求上输入凭据,从而使单一登录无效。The prompt=login claim forces the user to enter their credentials on that request, which negates single sign-on. prompt=none 声明完全相反。The prompt=none claim is the opposite. 此声明确保不会向用户显示任何交互提示。This claim ensures that the user isn't presented with any interactive prompt at. 如果请求无法通过单一登录以无提示方式完成,则 Microsoft 标识平台终结点将返回一个错误。If the request can't be completed silently via single sign-on, the Microsoft identity platform endpoint returns an error. prompt=consent 声明将在用户登录后触发 OAuth 同意对话框。The prompt=consent claim triggers the OAuth consent dialog after the user signs in. 该对话框要求用户向应用授予权限。The dialog asks the user to grant permissions to the app.
login_hint 可选Optional 如果事先知道用户名,可以使用此参数预先填充用户登录页的用户名/电子邮件地址字段。You can use this parameter to pre-fill the username and email address field of the sign-in page for the user, if you know the username ahead of time. 通常,应用在已经使用 preferred_username 声明从前次登录提取用户名后,会在重新身份验证时使用此参数。Often, apps use this parameter during reauthentication, after already extracting the username from an earlier sign-in by using the preferred_username claim.
domain_hint 可选Optional 联合目录中的用户领域。The realm of the user in a federated directory. 这会跳过用户在登录页面上经历的基于电子邮件的发现过程,从而实现更加流畅的用户体验。This skips the email-based discovery process that the user goes through on the sign-in page, for a slightly more streamlined user experience. 对于通过本地目录(例如 AD FS)联合的租户,这通常会由于现有登录会话而导致无缝登录。For tenants that are federated through an on-premises directory like AD FS, this often results in a seamless sign-in because of the existing login session.

此时,系统会提示用户输入凭据并完成身份验证。At this point, the user is prompted to enter their credentials and complete the authentication. Microsoft 标识平台终结点将验证用户是否已许可 scope 查询参数中指定的权限。The Microsoft identity platform endpoint verifies that the user has consented to the permissions indicated in the scope query parameter. 如果用户未许可其中的任何权限,Microsoft 标识平台终结点会提示用户许可所需的权限。If the user hasn't consented to any of those permissions, the Microsoft identity platform endpoint prompts the user to consent to the required permissions. 阅读有关权限、许可与多租户应用的详细信息。You can read more about permissions, consent, and multi-tenant apps.

用户经过身份验证并许可后,Microsoft 标识平台终结点会使用 response_mode 参数中指定的方法,将响应返回到位于指定重定向 URI 处的应用。After the user authenticates and grants consent, the Microsoft identity platform endpoint returns a response to your app at the indicated redirect URI by using the method specified in the response_mode parameter.

成功的响应Successful response

使用 response_mode=form_post 时的成功响应如下所示:A successful response when you use response_mode=form_post looks like this:

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

id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345
参数Parameter 说明Description
id_token 应用请求的 ID 令牌。The ID token that the app requested. 可以使用 id_token 参数验证用户的标识,开始与用户建立会话。You can use the id_token parameter to verify the user's identity and begin a session with the user. 有关 ID 令牌及其内容的详细信息,请参阅 id_tokens 参考For more information about ID tokens and their contents, see the id_tokens reference.
state 如果请求中包含 state 参数,响应中就应该出现相同的值。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

也可以将错误响应发送到重定向 URI,使应用能够处理这些响应。Error responses might also be sent to the redirect URI so that the app can handle them. 错误响应如下所示:An error response looks like this:

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
error 可用于对发生的错误分类以及对错误做出反应的错误代码字符串。An error code string that you can use to classify types of errors that occur, and to react to errors.
error_description 帮助识别身份验证错误根本原因的特定错误消息。A specific error message that can help you identify the root cause of an authentication error.

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

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

错误代码Error code 说明Description 客户端操作Client action
invalid_request 协议错误,例如,缺少必需的参数。Protocol error, such as a missing, required parameter. 修复并重新提交请求。Fix and resubmit the request. 这通常是在初始测试期间捕获的开发错误。This is a development error that typically is caught during initial testing.
unauthorized_client 客户端应用程序无法请求授权代码。The client application can't request an authorization code. 客户端应用程序未注册到 Azure AD 中或者未添加到用户的 Azure AD 租户时,通常会出现这种情况。This usually occurs when the client application isn't registered in Azure AD or isn't added to the user's Azure AD tenant. 应用程序可以提示用户,说明如何安装应用程序并将其添加到 Azure AD。The application can prompt the user with instructions to install the application and add it to Azure AD.
access_denied 资源所有者拒绝许可。The resource owner denied consent. 客户端应用程序可以通知用户,除非用户许可,否则无法继续。The client application can notify the user that it can't proceed unless the user consents.
unsupported_response_type 授权服务器不支持请求中的响应类型。The authorization server does not support the response type in the request. 修复并重新提交请求。Fix and resubmit the request. 这通常是在初始测试期间捕获的开发错误。This is a development error that typically is caught during initial testing.
server_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 because of a temporary error.
temporarily_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 because of a temporary condition.
invalid_resource 目标资源无效,原因是它不存在,Azure AD 找不到它,或者未正确配置。The target resource is invalid because either it does not exist, Azure AD can't find it, or it isn't correctly configured. 这表示未在租户中配置该资源(如果存在)。This indicates that the resource, if it exists, hasn't been configured in the tenant. 应用程序可以提示用户,说明如何安装应用程序并将其添加到 Azure AD。The application can prompt the user with instructions for installing the application and adding it to Azure AD.

验证 ID 令牌Validate the ID token

仅接收 id_token 不足以对用户进行身份验证;必须验证 id_token 的签名,并按照应用的要求验证令牌中的声明。Just receiving an id_token isn't sufficient to authenticate the user; you must validate the id_token's signature and verify the claims in the token per your app's requirements. Microsoft 标识平台终结点使用 JSON Web 令牌 (JWT) 和公钥加密对令牌进行签名并验证其是否有效。The Microsoft identity platform endpoint uses JSON Web Tokens (JWTs) and public key cryptography to sign tokens and verify that they're 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 do the validation there. 验证 id_token 的签名后,需要验证一些声明。Once you've validated the signature of the id_token, there are a few claims you'll be required to verify. 有关详细信息,请参阅 id_token 参考,其中包括验证令牌有关签名密钥滚动更新的重要信息See the id_token reference for more information, including Validating Tokens and Important Information About Signing Key Rollover. 我们建议利用库来分析和验证令牌 - 对于大多数语言和平台至少有一个可用。We recommend making use of a library for parsing and validating tokens - there is at least one available for most languages and platforms.

可能还希望根据自己的方案验证其他声明。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.
  • 确保用户拥有正确的授权/权限Ensuring the user has proper authorization/privileges
  • 确保身份验证具有一定的强度,例如多重身份验证。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. 此信息可用于显示、记录和个性化等。This information can be used for display, records, personalization, etc.

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

如果希望将用户从应用中注销,仅仅是清除应用的 Cookie 或结束用户会话并不足够。When you want to sign out the user from your app, it isn't sufficient to clear your app's cookies or otherwise end the user's session. 还必须将用户重定向到 Microsoft 标识平台终结点才能注销。如果不这样做,用户不需要再次输入凭据就能重新通过应用的身份验证,因为他们与 Microsoft 标识平台终结点之间存在有效的单一登录会话。You must also redirect the user to the Microsoft identity platform endpoint to sign out. If you don't do this, the user reauthenticates to your app without entering their credentials again, because they will have a valid single sign-in session with the Microsoft identity platform endpoint.

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

GET https://login.partner.microsoftonline.cn/common/oauth2/v2.0/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
参数Parameter 条件Condition 说明Description
post_logout_redirect_uri 建议Recommended 用户在成功注销后将重定向到的 URL。如果不包括参数,将向用户显示一条 Microsoft 标识平台终结点生成的常规消息。The URL that the user is redirected to after successfully signing out. If the parameter isn't included, the user is shown a generic message that's generated by the Microsoft identity platform endpoint. 此 URL 必须与在应用注册门户中为应用程序注册的重定向 URI 之一匹配。This URL must match one of the redirect URIs registered for your application in the app registration portal.

单一登录Single sign-out

将用户重定向到 end_session_endpoint 时,Microsoft 标识平台终结点将从浏览器中清除用户的会话。When you redirect the user to the end_session_endpoint, the Microsoft identity platform endpoint clears the user's session from the browser. 要使这些应用程序能够同时注销用户,Microsoft 标识平台终结点会将 HTTP GET 请求发送到用户当前登录到的所有应用程序的注册 LogoutUrlTo enable those applications to sign the user out simultaneously, the Microsoft identity platform endpoint 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. 可以从应用注册门户设置 LogoutUrlYou can set the LogoutUrl from the app registration portal.

协议图:访问令牌获取Protocol diagram: Access token acquisition

许多 Web 应用不仅需要将用户登录,而且还要代表该用户使用 OAuth 来访问 Web 服务。Many web apps need to not only sign the user in, but also to access a web service on behalf of the user by using OAuth. 此方案合并了用于对用户进行身份验证的 OpenID Connect,同时会获取授权代码,用于通过 OAuth 授权代码流来获取访问令牌。This scenario combines OpenID Connect for user authentication while simultaneously getting an authorization code that you can use to get access tokens if you are using the OAuth authorization code flow.

完整的 OpenID Connect 登录和令牌获取流如下图所示。The full OpenID Connect sign-in and token acquisition flow looks similar to the next diagram. 本文的后续部分详细介绍每个步骤。We describe each step in detail in the next sections of the article.

OpenID Connect 协议:令牌获取

获取访问令牌Get access tokens

若要获取访问令牌,请修改登录请求:To acquire access tokens, modify the sign-in request:

// Line breaks are for legibility only.

GET https://login.partner.microsoftonline.cn/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e        // Your registered Application ID
&response_type=id_token%20code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F       // Your registered redirect URI, URL encoded
&response_mode=form_post                              // 'form_post' or 'fragment'
&scope=openid%20                                      // Include both 'openid' and scopes that your app needs
offline_access%20
https%3A%2F%2Fmicrosoftgraph.chinacloudapi.cn%2Fuser.read
&state=12345                                          // Any value, provided by your app
&nonce=678910                                         // Any value, provided by your app

Tip

单击以下链接执行此请求!Click the following link to execute this request. 登录后,浏览器将重定向到 https://localhost/myapp/,且地址栏中有一个 ID 令牌和一个代码。After you sign in, your browser is redirected to https://localhost/myapp/, with an ID token and a code in the address bar. 请注意,此请求使用 response_mode=fragment(仅用于演示)。Note that this request uses response_mode=fragment for demonstration purposes only. 建议使用 response_mode=form_postWe recommend that you use response_mode=form_post. https://login.partner.microsoftonline.cn/common/oauth2/v2.0/authorize...https://login.partner.microsoftonline.cn/common/oauth2/v2.0/authorize...

通过使用 response_type=id_token code 在请求中包含权限范围,Microsoft 标识平台终结点可确保用户已经许可 scope 查询参数中指示的权限。By including permission scopes in the request and by using response_type=id_token code, the Microsoft identity platform endpoint ensures that the user has consented to the permissions indicated in the scope query parameter. v2.0 终结点会将授权代码返回给应用,以交换访问令牌。It returns an authorization code to your app to exchange for an access token.

成功的响应Successful response

使用 response_mode=form_post 后的成功响应如下所示:A successful response from using response_mode=form_post looks like this:

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

id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&state=12345
参数Parameter 说明Description
id_token 应用请求的 ID 令牌。The ID token that the app requested. 可以使用 ID 令牌验证用户的标识,开始与用户建立会话。You can use the ID token to verify the user's identity and begin a session with the user. 有关 ID 令牌及其内容的详细信息,请参阅 id_tokens 参考You'll find more details about ID tokens and their contents in the id_tokens reference.
code 应用请求的授权代码。The authorization code that the app requested. 应用可以使用授权代码请求目标资源的访问令牌。The app can use the authorization code to request an access token for the target resource. 授权代码的生存期较短。An authorization code is short-lived. 通常,授权代码在大约 10 分钟后即会过期。Typically, an authorization code expires in about 10 minutes.
state 如果请求中包含 state 参数,响应中就应该出现相同的值。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

也可以将错误响应发送到重定向 URI,使应用能够适当地处理这些响应。Error responses might also be sent to the redirect URI so that the app can handle them appropriately. 错误响应如下所示:An error response looks like this:

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
error 可用于对发生的错误分类以及对错误做出反应的错误代码字符串。An error code string that you can use to classify types of errors that occur, and to react to errors.
error_description 帮助识别身份验证错误根本原因的特定错误消息。A specific error message that can help you identify the root cause of an authentication error.

有关可能的错误代码和建议的客户端操作的说明,请参阅 授权终结点错误的错误代码For a description of possible error codes and recommended client responses, see Error codes for authorization endpoint errors.

获取授权代码和 ID 令牌之后,可将用户登录,并代表用户获取访问令牌。When you have an authorization code and an ID token, you can sign the user in and get access tokens on their behalf. 要将用户登录,必须 完全根据说明验证 ID 令牌。To sign the user in, you must validate the ID token exactly as described. 若要获取访问令牌,请遵循 OAuth 代码流文档中所述的步骤。To get access tokens, follow the steps described in OAuth code flow documentation.