Microsoft 身分識別平台和 OAuth 2.0 授權碼流程Microsoft identity platform and OAuth 2.0 authorization code flow

適用範圍:Applies to:
  • Microsoft 身分識別平台端點Microsoft identity platform endpoint

OAuth 2.0 授權碼授與可用於裝置上所安裝的應用程式中,以存取受保護的資源,例如 Web API。The OAuth 2.0 authorization code grant can be used in apps that are installed on a device to gain access to protected resources, such as web APIs. 使用 OAuth 2.0 的 Microsoft 身分識別平台實作,您可以新增登入及 API 存取您的行動和桌面應用程式。Using the Microsoft identity platform implementation of OAuth 2.0, you can add sign in and API access to your mobile and desktop apps. 本指南不限於特定語言,其中說明如何在不使用任何 Azure 開放原始碼驗證程式庫的情況下,傳送和接收 HTTP 訊息。This guide is language-independent, and describes how to send and receive HTTP messages without using any of the Azure open-source authentication libraries.

注意

並非所有的 Azure Active Directory 案例和功能會受到 Microsoft 身分識別平台的端點。Not all Azure Active Directory scenarios & features are supported by the Microsoft identity platform endpoint. 若要判斷是否應該使用 Microsoft 身分識別平台的端點,請參閱Microsoft 身分識別平台限制To determine if you should use the Microsoft identity platform endpoint, read about Microsoft identity platform limitations.

如需 OAuth 2.0 授權碼流程的說明,請參閱 OAuth 2.0 規格的 4.1 節The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. 它用來執行驗證和授權,在大部分的應用程式類型,包括web 應用程式原生安裝的應用程式It's used to perform authentication and authorization in the majority of app types, including web apps and natively installed apps. 此流程可讓應用程式安全地取得可用來存取受保護的 Microsoft 身分識別平台端點資源的 access_token。The flow enables apps to securely acquire access_tokens that can be used to access resources secured by the Microsoft identity platform endpoint.

通訊協定圖表Protocol diagram

概括而言,原生/行動應用程式的整個驗證流程看起來像是這樣:At a high level, the entire authentication flow for a native/mobile application looks a bit like this:

OAuth 授權碼流程

要求授權碼Request an authorization code

授權碼流程始於用戶端將使用者導向 /authorize 端點。The authorization code flow begins with the client directing the user to the /authorize endpoint. 在這項要求中,用戶端會指出必須向使用者索取的權限:In this request, the client indicates the permissions it needs to acquire from the user:

// Line breaks for legibility only

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&state=12345

提示

按一下下面的連結以執行此要求!Click the link below to execute this request! 登入之後,您的瀏覽器應重新導向至在位址列中有 codehttps://localhost/myapp/After signing in, your browser should be redirected to https://localhost/myapp/ with a code in the address bar. https://login.microsoftonline.com/common/oauth2/v2.0/authorize...https://login.microsoftonline.com/common/oauth2/v2.0/authorize...

參數Parameter 必要/選用Required/optional 描述Description
tenant 必要required 要求路徑中的 {tenant} 值可用來控制可登入應用程式的人員。The {tenant} value in the path of the request can be used to control who can sign into the application. 允許的值為 commonorganizationsconsumers 及租用戶識別碼。The allowed values are common, organizations, consumers, and tenant identifiers. 如需更多詳細資訊,請參閱 通訊協定基本概念For more detail, see protocol basics.
client_id 必要required 應用程式 (用戶端) 識別碼Azure 入口網站-應用程式註冊指派給您的應用程式的體驗。The Application (client) ID that the Azure portal – App registrations experience assigned to your app.
response_type 必要required 授權碼流程必須包含 codeMust include code for the authorization code flow.
redirect_uri 必要required 應用程式的 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. 對於原生和行動應用程式,請使用 https://login.microsoftonline.com/common/oauth2/nativeclient 的預設值。For native & mobile apps, you should use the default value of https://login.microsoftonline.com/common/oauth2/nativeclient.
scope 必要required 您要使用者同意的 範圍 空格分隔清單。A space-separated list of scopes that you want the user to consent to.
response_mode 建議使用recommended 指定將產生的權杖送回到應用程式所應該使用的方法。Specifies the method that should be used to send the resulting token back to your app. 可以是下列其中一項:Can be one of the following:

- query
- fragment
- form_post

query 會提供程式碼,以作為重新導向 URI 的查詢字串參數。query provides the code as a query string parameter on your redirect URI. 如果您要求使用隱含流程的識別碼權杖時,就無法使用query中所指定OpenID 規格。如果您只要求程式碼,您可以使用 queryfragmentform_postIf you're requesting an ID token using the implicit flow, you can't use query as specified in the OpenID spec. If you're requesting just the code, you can use query, fragment, or form_post. form_post 會執行 POST,其中包含您重新導向 URI 的程式碼。form_post executes a POST containing the code to your redirect URI. 如需詳細資訊,請參閱 OpenID Connect 通訊協定For more info, see OpenID Connect protocol.
state 建議使用recommended 同樣會隨權杖回應傳回之要求中所包含的值。A value included in the request that will also be 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 value can also encode information about the user's state in the app before the authentication request occurred, such as the page or view they were on.
prompt 選用optional 表示需要的使用者互動類型。Indicates the type of user interaction that is required. 此時唯有 loginnoneconsent 是有效值。The only valid values at this time are login, none, and consent.

- prompt=login 會強制使用者在該要求上輸入認證,否定單一登入。- prompt=login will force the user to enter their credentials on that request, negating single-sign on.
- prompt=none 則相反-它會確保使用者不顯示任何互動式提示。- prompt=none is the opposite - it will ensure that the user isn't presented with any interactive prompt whatsoever. 如果要求不能透過單一登入以無訊息方式完成,Microsoft 身分識別平台端點會傳回interaction_required時發生錯誤。If the request can't be completed silently via single-sign on, the Microsoft identity platform endpoint will return an interaction_required error.
- prompt=consent 會在使用者登入之後觸發 OAuth 同意對話方塊,詢問使用者是否要授與權限給應用程式。- prompt=consent will trigger the OAuth consent dialog after the user signs in, asking the user to grant permissions to the app.
login_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 will use this parameter during re-authentication, having already extracted the username from a previous sign-in using the preferred_username claim.
domain_hint 選用optional 可以是 consumersorganizations 其中一個。Can be one of consumers or organizations.

如果包含,它會略過電子郵件為基礎的探索程序,使用者會經歷在登入頁面上,導致稍微更流暢的使用者體驗。If included, it will skip the email-based discovery process that user goes through on the sign-in page, leading to a slightly more streamlined user experience. 通常應用程式會在重新驗證 (擷取上一次登入的 tid ) 期間使用此參數。Often apps will use this parameter during re-authentication, by extracting the tid from a previous sign-in. 如果 tid 宣告值是 9188040d-6c67-4c5b-b112-36a304b66dad,您應該使用 domain_hint=consumersIf the tid claim value is 9188040d-6c67-4c5b-b112-36a304b66dad, you should use domain_hint=consumers. 否則,使用 domain_hint=organizationsOtherwise, use domain_hint=organizations.
code_challenge_method 選用optional 用來為 code_challenge 參數編碼 code_verifier 的方法。The method used to encode the code_verifier for the code_challenge parameter. 可為下列其中一個值:Can be one of the following values:

- plain
- S256

如果排除,則當包含 code_challenge 時,會假設 code_challenge 是純文字。If excluded, code_challenge is assumed to be plaintext if code_challenge is included. Microsoft 身分識別平台支援兩者plainS256Microsoft identity platform supports both plain and S256. 如需詳細資訊,請參閱 PKCE RFCFor more information, see the PKCE RFC.
code_challenge 選用optional 用來透過來自原生用戶端的「代碼交換的證明金鑰」(PKCE) 保護授權碼授與。Used to secure authorization code grants via Proof Key for Code Exchange (PKCE) from a native client. 如果包含 code_challenge_method,則為必要參數。Required if code_challenge_method is included. 如需詳細資訊,請參閱 PKCE RFCFor more information, see the PKCE RFC.

此時,會要求使用者輸入其認證並完成驗證。At this point, the user will be asked to enter their credentials and complete the authentication. Microsoft 身分識別平台端點也會確保使用者已經同意中指出的權限scope查詢參數。The Microsoft identity platform endpoint will also ensure that the user has consented to the permissions indicated in the scope query parameter. 如果使用者未曾同意這些權限的任何一項,就會要求使用者同意要求的權限。If the user has not consented to any of those permissions, it will ask the user to consent to the required permissions. 這裡提供權限、同意與多租用戶應用程式的詳細資料。Details of permissions, consent, and multi-tenant apps are provided here.

一旦使用者驗證,並授與同意,Microsoft 身分識別平台端點會將回應傳回給您的應用程式所指定redirect_uri,使用中指定的方法response_mode參數。Once the user authenticates and grants consent, the Microsoft identity platform endpoint will return a response to your app at the indicated redirect_uri, using the method specified in the response_mode parameter.

成功回應Successful response

使用 response_mode=query 的成功回應如下所示:A successful response using response_mode=query looks like:

GET https://login.microsoftonline.com/common/oauth2/nativeclient?
code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
&state=12345
參數Parameter 描述Description
code 應用程式要求的 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, typically they 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:

GET https://login.microsoftonline.com/common/oauth2/nativeclient?
error=access_denied
&error_description=the+user+canceled+the+authentication
參數Parameter 描述Description
error 用以分類發生的錯誤類型與回應錯誤的錯誤碼字串。An error code string that can be used to classify types of errors that occur, and can be used to react to errors.
error_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_request 通訊協定錯誤,例如遺漏必要的參數。Protocol error, such as a missing required parameter. 修正並重新提交要求。Fix and resubmit the request. 這是通常會在初始測試期間擷取到的開發錯誤。This is a development error typically caught during initial testing.
unauthorized_client 用戶端應用程式不允許要求授權碼。The client application isn't permitted to request an authorization code. 當用戶端應用程式未在 Azure AD 中註冊,或不會新增至使用者的 Azure AD 租用戶時,通常會發生此錯誤。This error 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 instruction for installing the application and adding it to Azure AD.
access_denied 資源擁有者拒絕同意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 typically 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 to 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 it does not exist, Azure AD can't find it, or it's not correctly configured. 此錯誤表示尚未在租用戶中設定資源 (如果存在)。This error 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.
login_required 找到太多使用者或找不到使用者Too many or no users found 用戶端已要求無訊息驗證 (prompt=none),但找不到單一使用者。The client requested silent authentication (prompt=none), but a single user could not found. 這可能表示工作階段中有多個作用中使用者,或沒有任何使用者。This may mean there are multiple users active in the session, or no users. 這會考慮選擇租用戶 (例如,如果有使用中的兩個 Azure AD 帳戶和一個 Microsoft 帳戶,和consumers選擇,則會使用無訊息的驗證)。This takes into account the tenant chosen (for example, if there are two Azure AD accounts active and one Microsoft account, and consumers is chosen, silent authentication will work).
interaction_required 要求需要使用者互動。The request requires user interaction. 必須進行其他驗證步驟或同意。An additional authentication step or consent is required. 請在不使用 prompt=none 的情況下重試要求。Retry the request without prompt=none.

要求存取權杖Request an access token

取得 authorization_code 並獲得使用者授權之後,現在即可兌換所需資源之 access_tokencodeNow that you've acquired an authorization_code and have been granted permission by the user, you can redeem the code for an access_token to the desired resource. 做法是將 POST 要求傳送給 /token 端點:Do this by sending a POST request to the /token endpoint:

// Line breaks for legibility only

POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&grant_type=authorization_code
&client_secret=JqQX2PNo9bpM0uEihUPzyrh    // NOTE: Only required for web apps

提示

嘗試在 Postman 中執行這項要求!Try executing this request in Postman! (別忘了取代 code) 在 Postman 中執行(Don't forget to replace the code) Run in Postman

參數Parameter 必要/選用Required/optional 描述Description
tenant 必要required 要求路徑中的 {tenant} 值可用來控制可登入應用程式的人員。The {tenant} value in the path of the request can be used to control who can sign into the application. 允許的值為 commonorganizationsconsumers 及租用戶識別碼。The allowed values are common, organizations, consumers, and tenant identifiers. 如需更多詳細資訊,請參閱 通訊協定基本概念For more detail, see protocol basics.
client_id 必要required (用戶端) 應用程式識別碼Azure 入口網站-應用程式註冊指派給您的應用程式的頁面。The Application (client) ID that the Azure portal – App registrations page assigned to your app.
grant_type 必要required 必須是授權碼流程的 authorization_codeMust be authorization_code for the authorization code flow.
scope 必要required 範圍的空格分隔清單。A space-separated list of scopes. 在此階段中要求的範圍必須相當於或為第一個階段中所要求的範圍子集。The scopes requested in this leg must be equivalent to or a subset of the scopes requested in the first leg. 如果這個要求中指定的範圍遍及多個資源伺服器,Microsoft 身分識別平台端點會傳回第一個範圍中指定資源的權杖。If the scopes specified in this request span multiple resource server, then the Microsoft identity platform endpoint will return a token for the resource specified in the first scope. 如需範圍的詳盡說明,請參閱 權限、同意和範圍For a more detailed explanation of scopes, refer to permissions, consent, and scopes.
code 必要required 您在流程的第一個階段中取得的 authorization_code。The authorization_code that you acquired in the first leg of the flow.
redirect_uri 必要required 用來取得 authorization_code 的相同 redirect_uri 值。The same redirect_uri value that was used to acquire the authorization_code.
client_secret Web Apps 所需required for web apps 您在應用程式註冊入口網站中為應用程式建立的應用程式密碼。The application secret that you created in the app registration portal for your app. 您不應該在原生應用程式中使用應用程式祕密,因為 client_secret 無法可靠地儲存在裝置上。You shouldn't use the application secret in a native app because client_secrets can't be reliably stored on devices. 您需要 web 應用程式和 web Api,能夠將 client_secret 安全地儲存在伺服器端。It's required for web apps and web APIs, which have the ability to store the client_secret securely on the server side. 用戶端密碼必須在傳送之前先進行 URL 編碼。The client secret must be URL-encoded before being sent.
code_verifier 選用optional 用來取得 authorization_code 的相同 code_verifier。The same code_verifier that was used to obtain the authorization_code. 如果在授權碼授與要求中已使用 PKCE,則為必要參數。Required if PKCE was used in the authorization code grant request. 如需詳細資訊,請參閱 PKCE RFCFor more information, see the PKCE RFC.

成功回應Successful response

成功的權杖回應如下:A successful token response will look like:

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "token_type": "Bearer",
    "expires_in": 3599,
    "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fuser.read",
    "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
    "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
}
參數Parameter 描述Description
access_token 请求的访问令牌。The requested access token. 應用程式可以使用這個權杖驗證受保護的資源,例如 Web API。The app can use this token to authenticate to the secured resource, such as a web API.
token_type 表示權杖類型值。Indicates the token type value. Azure AD 唯一支援的類型是 Bearer。The only type that Azure AD supports is Bearer
expires_in 存取權杖的有效期 (以秒為單位)。How long the access token is valid (in seconds).
scope access_token 有效的範圍。The scopes that the access_token is valid for.
refresh_token OAuth 2.0 重新整理權杖。An OAuth 2.0 refresh token. 應用程式可以使用這個權杖,在目前的存取權杖過期之後,取得其他的存取權杖。The app can use this token acquire additional access tokens after the current access token expires. Refresh_token 的有效期很長,而且可以用來延長保留資源存取權的時間。Refresh_tokens are long-lived, and can be used to retain access to resources for extended periods of time. 如需有關重新整理存取權杖的詳細資訊,請參閱下一節For more detail on refreshing an access token, refer to the section below.
附註: 只在要求 offline_access 範圍時提供。Note: Only provided if offline_access scope was requested.
id_token JSON Web 權杖 (JWT)。A JSON Web Token (JWT). 應用程式可以將這個權杖的區段解碼,來要求已登入使用者的相關資訊。The app can decode the segments of this token to request information about the user who signed in. 應用程式可以快取並顯示值,但不應依賴這些值來取得任何授權或安全性界限。The app can cache the values and display them, but it should not rely on them for any authorization or security boundaries. 如需有關 id_token 的詳細資訊,請參閱 id_token referenceFor more information about id_tokens, see the id_token reference.
附註: 只在要求 openid 範圍時提供。Note: Only provided if openid scope was requested.

錯誤回應Error response

錯誤回應格式如下:Error responses will look like:

{
  "error": "invalid_scope",
  "error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope https://foo.microsoft.com/mail.read is not valid.\r\nTrace ID: 255d1aef-8c98-452f-ac51-23d051240864\r\nCorrelation ID: fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7\r\nTimestamp: 2016-01-09 02:02:12Z",
  "error_codes": [
    70011
  ],
  "timestamp": "2016-01-09 02:02:12Z",
  "trace_id": "255d1aef-8c98-452f-ac51-23d051240864",
  "correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7"
}
參數Parameter 描述Description
error 用以分類發生的錯誤類型與回應錯誤的錯誤碼字串。An error code string that can be used to classify types of errors that occur, and can be used to react to errors.
error_description 協助開發人員識別驗證錯誤根本原因的特定錯誤訊息。A specific error message that can help a developer identify the root cause of an authentication error.
error_codes 有助於診斷的 STS 特定錯誤碼清單。A list of STS-specific error codes that can help in diagnostics.
timestamp 發生錯誤的時間。The time at which the error occurred.
trace_id 有助於診斷的要求唯一識別碼。A unique identifier for the request that can help in diagnostics.
correlation_id 有助於跨元件診斷的要求唯一識別碼。A unique identifier for the request that can help in diagnostics across components.

權杖端點錯誤的錯誤碼Error codes for token endpoint errors

錯誤碼Error Code 描述Description 用戶端動作Client Action
invalid_request 通訊協定錯誤,例如遺漏必要的參數。Protocol error, such as a missing required parameter. 修正並重新提交要求Fix and resubmit the request
invalid_grant 授權碼或 PKCE 代碼驗證器無效或已過期。The authorization code or PKCE code verifier is invalid or has expired. 嘗試向 /authorize 端點提出新的要求,並確認 code_verifier 參數正確。Try a new request to the /authorize endpoint and verify that the code_verifier parameter was correct.
unauthorized_client 驗證的用戶端未獲授權使用此授權授與類型。The authenticated client isn't authorized to use this authorization grant type. 當用戶端應用程式未在 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 instruction for installing the application and adding it to Azure AD.
invalid_client 用戶端驗證失敗。Client authentication failed. 用戶端認證無效。The client credentials aren't valid. 若要修正,應用程式系統管理員必須更新認證。To fix, the application administrator updates the credentials.
unsupported_grant_type 授權伺服器不支援授權授與類型。The authorization server does not support the authorization grant type. 變更要求中的授與類型。Change the grant type in the request. 這種類型的錯誤應該只會在開發期間發生,並且會在初始測試期間偵測出來。This type of error should occur only during development and be detected during initial testing.
invalid_resource 目標資源無效,因為它不存在、 Azure AD 無法找到它,或是未正確設定。The target resource is invalid because it does not exist, Azure AD can't find it, or it's 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.
interaction_required 要求需要使用者互動。The request requires user interaction. 例如,必須進行其他驗證步驟。For example, an additional authentication step is required. 以相同資源重試要求。Retry the request with the same resource.
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.

使用存取權杖Use the access token

既然您已經成功取得 access_token,您就可以透過在 Authorization 標頭中包含權杖,在 Web API 的要求中使用權杖:Now that you've successfully acquired an access_token, you can use the token in requests to Web APIs by including it in the Authorization header:

提示

在 Postman 中執行這項要求!Execute this request in Postman! (先取代 Authorization 標頭) 在 Postman 中執行(Replace the Authorization header first) Run in Postman

GET /v1.0/me/messages
Host: https://graph.microsoft.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...

重新整理存取權杖Refresh the access token

Access_token 有效期很短,且您必須在其到期後重新整理,才能繼續存取資源。Access_tokens are short lived, and you must refresh them after they expire to continue accessing resources. 方法是:向 /token 端點送出另一個 POST 要求,這次提供 refresh_token,而不提供 codeYou can do so by submitting another POST request to the /token endpoint, this time providing the refresh_token instead of the code. 重新整理權杖對用戶端已同意的所有權限都有效,因此,對 scope=mail.read 要求所發出的重新整理權杖可用於向 scope=api://contoso.com/api/UseResource 要求新的存取權杖。Refresh tokens are valid for all permissions that your client has already received consent for - thus, a refresh token issued on a request for scope=mail.read can be used to request a new access token for scope=api://contoso.com/api/UseResource.

重新整理權杖並沒有指定的存留期。Refresh tokens do not have specified lifetimes. 一般而言,重新整理權杖的存留期相當長。Typically, the lifetimes of refresh tokens are relatively long. 不過,在某些情況下,重新整理權杖會過期、遭到撤銷或對要執行的動作缺乏足夠的權限。However, in some cases, refresh tokens expire, are revoked, or lack sufficient privileges for the desired action. 應用程式必須預期並正確處理權杖發行端點所傳回的錯誤Your application needs to expect and handle errors returned by the token issuance endpoint correctly.

雖然重新整理權杖未撤銷用來取得新存取權杖時,您應該捨棄舊的重新整理權杖。Although refresh tokens aren't revoked when used to acquire new access tokens, you are expected to discard the old refresh token. OAuth 2.0 規格說:「 授權伺服器可能發出新的重新整理權杖,以案例在用戶端必須捨棄舊的重新整理權杖,並以新的重新整理權杖取代。The OAuth 2.0 spec says: "The authorization server MAY issue a new refresh token, in which case the client MUST discard the old refresh token and replace it with the new refresh token. 授權伺服器可以撤銷舊的重新整理權杖給用戶端發出新的重新整理權杖之後。 」The authorization server MAY revoke the old refresh token after issuing a new refresh token to the client."

// Line breaks for legibility only

POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&client_secret=JqQX2PNo9bpM0uEihUPzyrh      // NOTE: Only required for web apps

提示

嘗試在 Postman 中執行這項要求!Try executing this request in Postman! (別忘了取代 refresh_token) 在 Postman 中執行(Don't forget to replace the refresh_token) Run in Postman

參數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. 允許的值為 commonorganizationsconsumers 及租用戶識別碼。The allowed values are common, organizations, consumers, and tenant identifiers. 如需更多詳細資訊,請參閱 通訊協定基本概念For more detail, see protocol basics.
client_id 必要required 應用程式 (用戶端) 識別碼Azure 入口網站-應用程式註冊指派給您的應用程式的體驗。The Application (client) ID that the Azure portal – App registrations experience assigned to your app.
grant_type 必要required 必須是授權碼流程此階段的 refresh_tokenMust be refresh_token for this leg of the authorization code flow.
scope 必要required 範圍的空格分隔清單。A space-separated list of scopes. 在此階段中要求的範圍必須相當於或為原始 authorization_code 要求階段中所要求的範圍子集。The scopes requested in this leg must be equivalent to or a subset of the scopes requested in the original authorization_code request leg. 如果這個要求中指定的範圍遍及多個資源伺服器,Microsoft 身分識別平台端點會傳回第一個範圍中指定資源的權杖。If the scopes specified in this request span multiple resource server, then the Microsoft identity platform endpoint will return a token for the resource specified in the first scope. 如需範圍的詳盡說明,請參閱 權限、同意和範圍For a more detailed explanation of scopes, refer to permissions, consent, and scopes.
refresh_token 必要required 您在流程的第二個階段中取得的 refresh_token。The refresh_token that you acquired in the second leg of the flow.
client_secret Web Apps 所需required for web apps 您在應用程式註冊入口網站中為應用程式建立的應用程式密碼。The application secret that you created in the app registration portal for your app. 它應該不能在原生應用程式中,因為 client_secret 無法可靠地儲存在裝置上。It should not be used in a native app, because client_secrets can't be reliably stored on devices. 您需要 web 應用程式和 web Api,能夠將 client_secret 安全地儲存在伺服器端。It's required for web apps and web APIs, which have the ability to store the client_secret securely on the server side.

成功回應Successful response

成功的權杖回應如下:A successful token response will look like:

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "token_type": "Bearer",
    "expires_in": 3599,
    "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fuser.read",
    "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
    "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
}
參數Parameter 描述Description
access_token 请求的访问令牌。The requested access token. 應用程式可以使用這個權杖驗證受保護的資源,例如 Web API。The app can use this token to authenticate to the secured resource, such as a web API.
token_type 表示權杖類型值。Indicates the token type value. Azure AD 唯一支援的類型是 Bearer。The only type that Azure AD supports is Bearer
expires_in 存取權杖的有效期 (以秒為單位)。How long the access token is valid (in seconds).
scope access_token 有效的範圍。The scopes that the access_token is valid for.
refresh_token 新的 OAuth 2.0 重新整理權杖。A new OAuth 2.0 refresh token. 您應該用新取得的重新整理權杖取代舊的重新整理權杖,以確定盡可能保持重新整理權杖有效的時間。You should replace the old refresh token with this newly acquired refresh token to ensure your refresh tokens remain valid for as long as possible.
附註: 只在要求 offline_access 範圍時提供。Note: Only provided if offline_access scope was requested.
id_token 不帶正負號的 JSON Web Token (JWT)。An unsigned JSON Web Token (JWT). 應用程式可以將這個權杖的區段解碼,來要求已登入使用者的相關資訊。The app can decode the segments of this token to request information about the user who signed in. 應用程式可以快取並顯示值,但不應依賴這些值來取得任何授權或安全性界限。The app can cache the values and display them, but it should not rely on them for any authorization or security boundaries. 如需有關 id_token 的詳細資訊,請參閱 id_token referenceFor more information about id_tokens, see the id_token reference.
附註: 只在要求 openid 範圍時提供。Note: Only provided if openid scope was requested.

錯誤回應Error response

{
  "error": "invalid_scope",
  "error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope https://foo.microsoft.com/mail.read is not valid.\r\nTrace ID: 255d1aef-8c98-452f-ac51-23d051240864\r\nCorrelation ID: fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7\r\nTimestamp: 2016-01-09 02:02:12Z",
  "error_codes": [
    70011
  ],
  "timestamp": "2016-01-09 02:02:12Z",
  "trace_id": "255d1aef-8c98-452f-ac51-23d051240864",
  "correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7"
}
參數Parameter 描述Description
error 用以分類發生的錯誤類型與回應錯誤的錯誤碼字串。An error code string that can be used to classify types of errors that occur, and can be used to react to errors.
error_description 協助開發人員識別驗證錯誤根本原因的特定錯誤訊息。A specific error message that can help a developer identify the root cause of an authentication error.
error_codes 有助於診斷的 STS 特定錯誤碼清單。A list of STS-specific error codes that can help in diagnostics.
timestamp 發生錯誤的時間。The time at which the error occurred.
trace_id 有助於診斷的要求唯一識別碼。A unique identifier for the request that can help in diagnostics.
correlation_id 有助於跨元件診斷的要求唯一識別碼。A unique identifier for the request that can help in diagnostics across components.

如需錯誤碼及建議的用戶端動作的說明,請參閱權杖端點錯誤的錯誤碼For a description of the error codes and the recommended client action, see Error codes for token endpoint errors.