使用 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. 這會讓應用程式獲得應用程式識別碼,以及讓它可以接收權杖。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 registration.
  • 遵照提示進行,並建立新的應用程式。Follow the prompts and create a new application. 它並不重要如果它是 web 應用程式或本教學課程中,公用用戶端 (行動和桌面) 應用程式,但是如果您想要特定 web 應用程式或公用用戶端應用程式範例,請參閱我們快速入門It doesn't matter if it is a web application or a public client (mobile & desktop) application for this tutorial, but if you'd like specific examples for web applications or public client applications, check out our quickstarts.
    • [名稱] 為應用程式名稱,並能向使用者描述您的應用程式。Name is the application name and describes your application to end users.
    • 在 [支援的帳戶類型] 底下,選取 [任何組織目錄中的帳戶及個人的 Microsoft 帳戶] 。Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts.
    • 提供重新導向 URIProvide the Redirect URI. Web 應用程式,這是您的應用程式的基底 URL 的使用者可以登入。For Web Applications, this is the base URL of your app where users can sign in. 例如: http://localhost:12345For example, http://localhost:12345. 公用用戶端 (行動和桌面),Azure AD 會使用它來傳回權杖回應。For public client (mobile & desktop), Azure AD uses it to return token responses. 輸入應用程式特定的值。Enter a value specific to your application. 例如: http://MyFirstAADAppFor example, http://MyFirstAADApp.
  • 完成註冊後,Azure AD 會為指派您的應用程式唯一用戶端識別碼 (應用程式識別碼)。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.microsoftonline.com/{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. 請注意, 提供租使用者識別碼, 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.microsoftonline.com/{tenant}/oauth2/authorize",
    "token_endpoint": "https://login.microsoftonline.com/{tenant}/oauth2/token",
    "token_endpoint_auth_methods_supported":
    [
        "client_secret_post",
        "private_key_jwt",
        "client_secret_basic"
    ],
    "jwks_uri": "https://login.microsoftonline.com/common/discovery/keys"
    "userinfo_endpoint":"https://login.microsoftonline.com/{tenant}/openid/userinfo",
    ...
}

如果您的應用程式具有自訂簽署金鑰做為使用宣告對應功能的結果, 您必須附加appid包含應用程式識別碼的查詢參數, 才能取得指向jwks_uri應用程式簽署金鑰資訊的。If 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}/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e jwks_uri包含的。https://login.microsoftonline.com/{tenant}/discovery/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391eFor example: https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e contains a jwks_uri of https://login.microsoftonline.com/{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.
  • 要求必須包含 nonce 參數。The request must include the nonce parameter.

因此範例要求會看起來像這樣:So a sample request would look like this:

// Line breaks for legibility only

GET https://login.microsoftonline.com/{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
租用戶tenant 必要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.onmicrosoft.comcommonThe allowed values are tenant identifiers, for example, 8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or contoso.onmicrosoft.com or common for tenant-independent tokens
client_idclient_id 必要required 向 Azure AD 註冊應用程式時,指派給您應用程式的應用程式識別碼。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]、[應用程式註冊]、應用程式, 並在應用程式頁面上找到應用程式識別碼。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_types,例如 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. 支援的值為 form_post (HTTP 表單張貼) 和 fragment (URL 片段)。Supported 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.
狀態state 建議使用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. 此狀態也用於在驗證要求出現之前,於應用程式中編碼使用者的狀態資訊,例如之前所在的網頁或檢視。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.
狀態state 要求中包含的值,也會隨權杖回應傳回。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. 此狀態也用於在驗證要求出現之前,於應用程式中編碼使用者的狀態資訊,例如之前所在的網頁或檢視。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 Tokens (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.microsoftonline.com/common/oauth2/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F

參數Parameter 描述Description
post_logout_redirect_uripost_logout_redirect_uri 建議使用recommended 使用者在成功登出後應重新導向至的 URL。如果此參數,則會向使用者顯示一般訊息。The URL that the user should be redirected to after successful sign out. If 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 Apps 不僅需要將使用者登入,同時需要使用 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 以進行使用者驗證,同時使用 OAuth 授權碼流程取得 authorization_code,藉此取得 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.microsoftonline.com/{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

成功的回應 ( redirect_uri使用response_mode=form_post傳送至) 看起來像這樣: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_code 的有效期很短,通常約 10 分鐘後即到期。Authorization_codes are short lived, and typically expire after 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

錯誤回應可能也會傳送至 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