您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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.

备注

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 令牌** 的概念,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.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration

提示

试试看!Try it! 单击https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration以查看common租户配置。Click https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration to see the common tenants configuration.

{tenant} 可采用四个值的其中之一:The {tenant} can take one of four values:

“值”Value 描述Description
common 同时使用个人 Microsoft 帐户以及 Azure AD 的工作或学校帐户的用户可以登录到应用程序。Users with both a personal Microsoft account and 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.
consumers 仅拥有 Microsoft 个人帐户的用户可以登录到应用程序。Only users with a personal Microsoft account can sign in to the application.
8eaef023-2b34-4da1-9baa-8bc8c9d6a490contoso.onmicrosoft.com8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or contoso.onmicrosoft.com 只有来自特定 Azure AD 租户的用户(无论是具有工作帐户还是学校帐户的目录中的成员,还是具有个人 Microsoft 帐户的目录中的来宾)才能登录到应用程序。Only users from a specific Azure AD tenant (whether they are members in the directory with a work or school account, or they are guests in the directory with a personal Microsoft 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.microsoftonline.com\/{tenant}\/oauth2\/v2.0\/authorize",
  "token_endpoint": "https:\/\/login.microsoftonline.com\/{tenant}\/oauth2\/v2.0\/token",
  "token_endpoint_auth_methods_supported": [
    "client_secret_post",
    "private_key_jwt"
  ],
  "jwks_uri": "https:\/\/login.microsoftonline.com\/{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.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e 包含 https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391ejwks_uriFor example: https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e contains a jwks_uri of https://login.microsoftonline.com/{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.
  • 请求必须包含 nonce 参数。The request must include the nonce parameter.

重要

若要从 /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.microsoftonline.com/{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

提示

单击下面的链接可执行此请求。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.microsoftonline.com/common/oauth2/v2.0/authorize...https://login.microsoftonline.com/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 门户和应用注册体验的应用程序(客户端)ID分配给应用。The 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,应用可通过此 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. 此时唯一有效值为 login``noneconsentThe 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. 应用程序应该验证请求和响应中的状态值是否完全相同。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.microsoftonline.com/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 帐户进行身份验证的应用程序。However, the user may still be signed in to other applications that use Microsoft accounts for authentication. 要使这些应用程序能够同时注销用户,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. 如果要使用 OAuth 授权代码流,此方案合并了用于对用户进行身份验证的 OpenID Connect,同时将获取授权代码,用户可以使用该代码获取访问令牌。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.microsoftonline.com/{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%2Fgraph.microsoft.com%2Fuser.read
&state=12345                                          // Any value, provided by your app
&nonce=678910                                         // Any value, provided by your app

提示

单击下面的链接可执行此请求。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.microsoftonline.com/common/oauth2/v2.0/authorize...https://login.microsoftonline.com/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. 它将授权代码返回应用,以交换访问令牌。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_tokens引用中找到有关 ID 令牌及其内容的更多详细信息。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 如果请求中包含状态参数,响应中就应该出现相同的值。If a state parameter is included in the request, the same value should appear in the response. 应用程序应该验证请求和响应中的状态值是否完全相同。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.