了解如何在 Azure VM 上使用 Azure 資源受控識別來取得存取權杖How to use managed identities for Azure resources on an Azure VM to acquire an access token

適用於 Azure 資源的受控識別是 Azure Active Directory 的一項功能。Managed identities for Azure resources is a feature of Azure Active Directory. 每個支援適用於 Azure 資源的受控識別 Azure 服務均受限於其本身的時間表。Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. 在開始之前,請務必先檢閱資源的受控識別可用性狀態和已知問題Make sure you review the availability status of managed identities for your resource and known issues before you begin.

Azure 資源受控識別會在 Azure Active Directory 中為 Azure 服務提供自動受控識別。Managed identities for Azure resources provides Azure services with an automatically managed identity in Azure Active Directory. 您可以使用此身分識別來向任何支援 Azure AD 驗證的服務進行驗證,不需要任何您程式碼中的認證。You can use this identity to authenticate to any service that supports Azure AD authentication, without having credentials in your code.

本文提供各種取得權杖的程式碼和指令碼,以及處理權杖到期和 HTTP 錯誤等重要主題的指引。This article provides various code and script examples for token acquisition, as well as guidance on important topics such as handling token expiration and HTTP errors.

先決條件Prerequisites

  • 如果您不熟悉適用於 Azure 資源的受控識別功能,請參閱此概觀If you're not familiar with the managed identities for Azure resources feature, see this overview. 如果您沒有 Azure 帳戶,請先註冊免費帳戶,再繼續進行。If you don't have an Azure account, sign up for a free account before you continue.

如果您打算使用本文中的 Azure PowerShell 範例,請務必安裝最新版的 Azure PowerShellIf you plan to use the Azure PowerShell examples in this article, be sure to install the latest version of Azure PowerShell.

重要

  • 本文中的所有範例程式碼/指令碼都假設用戶端是在具有 Azure 資源受控識別的虛擬機器上執行。All sample code/script in this article assumes the client is running on a virtual machine with managed identities for Azure resources. 在 Azure 入口網站中使用虛擬機器「連線」功能,從遠端連線到您的虛擬機器。Use the virtual machine "Connect" feature in the Azure portal, to remotely connect to your VM. 如需有關在虛擬機器上啟用 Azure 資源受控識別的詳細資訊,請參閱使用 Azure 入口網站在虛擬機器上設定 Azure 資源受控識別,或其中一篇變化文章 (使用 PowerShell、CLI、範本或 Azure SDK)。For details on enabling managed identities for Azure resources on a VM, see Configure managed identities for Azure resources on a VM using the Azure portal, or one of the variant articles (using PowerShell, CLI, a template, or an Azure SDK).

重要

  • Azure 資源受控識別的安全性界限是一直都在使用的資源。The security boundary of managed identities for Azure resources, is the resource it's being used on. 所有在虛擬機器上執行的程式碼/指令碼,都可以針對其上提供的任何受控識別要求及擷取權杖。All code/scripts running on a virtual machine can request and retrieve tokens for any managed identities available on it.

總覽Overview

用戶端應用程式可以要求用於存取指定資源的 Azure 資源受控識別:僅限應用程式的存取權杖A client application can request managed identities for Azure resources app-only access token for accessing a given resource. 此權杖是以 Azure 資源受控識別服務原則為基礎The token is based on the managed identities for Azure resources service principal. 因此,用戶端不需要自行註冊就能取得本身服務主體下的存取權杖。As such, there is no need for the client to register itself to obtain an access token under its own service principal. 權杖在需要用戶端認證的服務對服務呼叫中適合作為持有人權杖。The token is suitable for use as a bearer token in service-to-service calls requiring client credentials.

使用 HTTP 取得權杖Get a token using HTTP Azure 資源受控識別權杖端點的通訊協定詳細資料Protocol details for managed identities for Azure resources token endpoint
使用適用於 .NET 的 Microsoft.Azure.Services.AppAuthentication 程式庫取得權杖Get a token using the Microsoft.Azure.Services.AppAuthentication library for .NET 從 .NET 用戶端使用 Microsoft.Azure.Services.AppAuthentication 程式庫的範例Example of using the Microsoft.Azure.Services.AppAuthentication library from a .NET client
使用 C# 取得權杖Get a token using C# 從 C# 用戶端使用 Azure 資源受控識別 REST 端點的範例Example of using managed identities for Azure resources REST endpoint from a C# client
使用 Java 取得權杖Get a token using Java 從 Java 用戶端使用 Azure 資源受控識別 REST 端點的範例Example of using managed identities for Azure resources REST endpoint from a Java client
使用 Go 取得權杖Get a token using Go 從 Go 用戶端使用 Azure 資源受控識別 REST 端點的範例Example of using managed identities for Azure resources REST endpoint from a Go client
使用 Azure PowerShell 取得權杖Get a token using Azure PowerShell 從 PowerShell 用戶端使用 Azure 資源受控識別 REST 端點的範例Example of using managed identities for Azure resources REST endpoint from a PowerShell client
使用 CURL 取得權杖Get a token using CURL 從 Bash/CURL 用戶端使用 Azure 資源受控識別 REST 端點的範例Example of using managed identities for Azure resources REST endpoint from a Bash/CURL client
處理權杖快取Handling token caching 處理過期存取權杖的指引Guidance for handling expired access tokens
錯誤處理Error handling 此指引可處理從 Azure 資源受控識別權杖端點傳回的 HTTP 錯誤Guidance for handling HTTP errors returned from the managed identities for Azure resources token endpoint
Azure 服務的資源識別碼Resource IDs for Azure services 取得所支援 Azure 服務資源識別碼的地方Where to get resource IDs for supported Azure services

使用 HTTP 取得權杖Get a token using HTTP

取得存取權杖的基本介面是以 REST 為基礎,如此可讓用戶端應用程式在可執行 HTTP REST 呼叫的虛擬機器上執行時,可以對其進行存取。The fundamental interface for acquiring an access token is based on REST, making it accessible to any client application running on the VM that can make HTTP REST calls. 這類似於 Azure AD 的程式設計模型,但用戶端會使用虛擬機器上的端點 (對比於 Azure AD 端點)。This is similar to the Azure AD programming model, except the client uses an endpoint on the virtual machine (vs an Azure AD endpoint).

使用 Azure Instance Metadata Service (IMDS) 端點 (建議) 的範例要求:Sample request using the Azure Instance Metadata Service (IMDS) endpoint (recommended):

GET 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' HTTP/1.1 Metadata: true
項目Element 描述Description
GET HTTP 指令動詞,指出您想要擷取端點中的資料。The HTTP verb, indicating you want to retrieve data from the endpoint. 在此案例中是 OAuth 存取權杖。In this case, an OAuth access token.
http://169.254.169.254/metadata/identity/oauth2/token 適用於 Instance Metadata Service 的 Azure 資源受控識別端點。The managed identities for Azure resources endpoint for the Instance Metadata Service.
api-version 一個查詢字串參數,指出 IMDS 端點的 API 版本。A query string parameter, indicating the API version for the IMDS endpoint. 請使用 API 2018-02-01 版或更新版本。Please use API version 2018-02-01 or greater.
resource 查詢字串參數,指出目標資源的應用程式識別碼 URI。A query string parameter, indicating the App ID URI of the target resource. 也會出現在所核發權杖的 aud (對象) 宣告中。It also appears in the aud (audience) claim of the issued token. 此範例會要求用來存取 Azure Resource Manager 的權杖,其中包含應用程式識別碼 URI https://management.azure.com/This example requests a token to access Azure Resource Manager, which has an App ID URI of https://management.azure.com/.
Metadata HTTP 要求標頭欄位,Azure 資源受控識別需要此元素以減輕伺服器端偽造要求 (SSRF) 攻擊。An HTTP request header field, required by managed identities for Azure resources as a mitigation against Server Side Request Forgery (SSRF) attack. 此值必須設定為 "true" (全部小寫)。This value must be set to "true", in all lower case.
object_id (選擇性) 查詢字串參數,指出要使用權杖的受控識別 object_id。(Optional) A query string parameter, indicating the object_id of the managed identity you would like the token for. 如果您的 VM 有多個使用者指派的受控識別,這會是必要項目。Required, if your VM has multiple user-assigned managed identities.
client_id (選擇性) 查詢字串參數,指出要使用權杖的受控識別 client_id。(Optional) A query string parameter, indicating the client_id of the managed identity you would like the token for. 如果您的 VM 有多個使用者指派的受控識別,這會是必要項目。Required, if your VM has multiple user-assigned managed identities.
mi_res_id (選擇性)查詢字串參數,指出 mi_res_id (Azure 資源識別碼) 的受管理的身分識別您想要的語彙基元。(Optional) A query string parameter, indicating the mi_res_id (Azure Resource ID) of the managed identity you would like the token for. 如果您的 VM 有多個使用者指派的受控識別,這會是必要項目。Required, if your VM has multiple user-assigned managed identities.

使用 Azure 資源受控識別 VM 擴充功能端點的範例要求 (已計劃在 2019 年 1 月淘汰) :Sample request using the managed identities for Azure resources VM Extension Endpoint (planned for deprecation in January 2019):

GET http://localhost:50342/oauth2/token?resource=https%3A%2F%2Fmanagement.azure.com%2F HTTP/1.1
Metadata: true
項目Element 描述Description
GET HTTP 指令動詞,指出您想要擷取端點中的資料。The HTTP verb, indicating you want to retrieve data from the endpoint. 在此案例中是 OAuth 存取權杖。In this case, an OAuth access token.
http://localhost:50342/oauth2/token Azure 資源受控識別端點,其中 50342 是預設連接埠且可設定。The managed identities for Azure resources endpoint, where 50342 is the default port and is configurable.
resource 查詢字串參數,指出目標資源的應用程式識別碼 URI。A query string parameter, indicating the App ID URI of the target resource. 也會出現在所核發權杖的 aud (對象) 宣告中。It also appears in the aud (audience) claim of the issued token. 此範例會要求用來存取 Azure Resource Manager 的權杖,其中包含應用程式識別碼 URI https://management.azure.com/This example requests a token to access Azure Resource Manager, which has an App ID URI of https://management.azure.com/.
Metadata HTTP 要求標頭欄位,Azure 資源受控識別需要此元素以減輕伺服器端偽造要求 (SSRF) 攻擊。An HTTP request header field, required by managed identities for Azure resources as a mitigation against Server Side Request Forgery (SSRF) attack. 此值必須設定為 "true" (全部小寫)。This value must be set to "true", in all lower case.
object_id (選擇性) 查詢字串參數,指出要使用權杖的受控識別 object_id。(Optional) A query string parameter, indicating the object_id of the managed identity you would like the token for. 如果您的 VM 有多個使用者指派的受控識別,這會是必要項目。Required, if your VM has multiple user-assigned managed identities.
client_id (選擇性) 查詢字串參數,指出要使用權杖的受控識別 client_id。(Optional) A query string parameter, indicating the client_id of the managed identity you would like the token for. 如果您的 VM 有多個使用者指派的受控識別,這會是必要項目。Required, if your VM has multiple user-assigned managed identities.

範例回應:Sample response:

HTTP/1.1 200 OK
Content-Type: application/json
{
  "access_token": "eyJ0eXAi...",
  "refresh_token": "",
  "expires_in": "3599",
  "expires_on": "1506484173",
  "not_before": "1506480273",
  "resource": "https://management.azure.com/",
  "token_type": "Bearer"
}
元素Element 描述Description
access_token 所要求的存取權杖。The requested access token. 呼叫受保護的 REST API 時,權杖會內嵌在 Authorization 要求標頭欄位中成為「持有人」權杖,以允許 API 驗證呼叫端。When calling a secured REST API, the token is embedded in the Authorization request header field as a "bearer" token, allowing the API to authenticate the caller.
refresh_token 並未由 Azure 資源受控識別使用。Not used by managed identities for Azure resources.
expires_in 存取權杖從發行到過期之前持續有效的秒數。The number of seconds the access token continues to be valid, before expiring, from time of issuance. 在權杖的 iat 宣告中可找到發行時間。Time of issuance can be found in the token's iat claim.
expires_on 存取權杖到期的時間範圍。The timespan when the access token expires. 日期以 "1970-01-01T0:0:0Z UTC" 起算的秒數表示 (對應至權杖的 exp 宣告)。The date is represented as the number of seconds from "1970-01-01T0:0:0Z UTC" (corresponds to the token's exp claim).
not_before 存取權杖生效且可被接受的時間範圍。The timespan when the access token takes effect, and can be accepted. 日期以 "1970-01-01T0:0:0Z UTC" 起算的秒數表示 (對應至權杖的 nbf 宣告)。The date is represented as the number of seconds from "1970-01-01T0:0:0Z UTC" (corresponds to the token's nbf claim).
resource 要求存取權杖所針對的資源,符合要求的 resource 查詢字串參數。The resource the access token was requested for, which matches the resource query string parameter of the request.
token_type 權杖的類型,即「持有人」存取權杖,表示此權杖的持有人可以存取資源。The type of token, which is a "Bearer" access token, which means the resource can give access to the bearer of this token.

使用適用於 .NET 的 Microsoft.Azure.Services.AppAuthentication 程式庫取得權杖Get a token using the Microsoft.Azure.Services.AppAuthentication library for .NET

對於 .NET 應用程式和函式,使用 Azure 資源受控識別的最簡單方式就是透過 Microsoft.Azure.Services.AppAuthentication 套件。For .NET applications and functions, the simplest way to work with managed identities for Azure resources is through the Microsoft.Azure.Services.AppAuthentication package. 該程式庫還能讓您使用來自 Visual Studio、Azure CLI 或 Active Directory 整合式驗證的使用者帳戶,在部署機器上以本機方式測試程式碼。This library will also allow you to test your code locally on your development machine, using your user account from Visual Studio, the Azure CLI, or Active Directory Integrated Authentication. 如需使用此程式庫之本機開發選項的詳細資訊,請參閱 Microsoft.Azure.Services.AppAuthentication 參考For more on local development options with this library, see the Microsoft.Azure.Services.AppAuthentication reference. 本節示範如何在您的程式碼中開始使用程式庫。This section shows you how to get started with the library in your code.

  1. Microsoft.Azure.Services.AppAuthenticationMicrosoft.Azure.KeyVault NuGet 套件的參考新增至應用程式。Add references to the Microsoft.Azure.Services.AppAuthentication and Microsoft.Azure.KeyVault NuGet packages to your application.

  2. 將下列程式碼新增至應用程式:Add the following code to your application:

    using Microsoft.Azure.Services.AppAuthentication;
    using Microsoft.Azure.KeyVault;
    // ...
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
    // OR
    var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
    

若要深入了解 Microsoft.Azure.Services.AppAuthentication 和它公開的作業,請參閱 Microsoft.Azure.Services.AppAuthentication 參考採用 Azure 資源受控識別的 App Service 和 KeyVault .NET 範例To learn more about Microsoft.Azure.Services.AppAuthentication and the operations it exposes, see the Microsoft.Azure.Services.AppAuthentication reference and the App Service and KeyVault with managed identities for Azure resources .NET sample.

使用 C# 取得權杖Get a token using C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization; 

// Build request to acquire managed identities for Azure resources token
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/");
request.Headers["Metadata"] = "true";
request.Method = "GET";

try
{
    // Call /token endpoint
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Pipe response Stream to a StreamReader, and extract access token
    StreamReader streamResponse = new StreamReader(response.GetResponseStream()); 
    string stringResponse = streamResponse.ReadToEnd();
    JavaScriptSerializer j = new JavaScriptSerializer();
    Dictionary<string, string> list = (Dictionary<string, string>) j.Deserialize(stringResponse, typeof(Dictionary<string, string>));
    string accessToken = list["access_token"];
}
catch (Exception e)
{
    string errorText = String.Format("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed");
}

使用 Java 取得權杖Get a token using Java

使用此 JSON 文件庫擷取使用 Java 的權杖。Use this JSON library to retrieve a token using Java.

import java.io.*;
import java.net.*;
import com.fasterxml.jackson.core.*;
 
class GetMSIToken {
    public static void main(String[] args) throws Exception {
 
        URL msiEndpoint = new URL("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/");
        HttpURLConnection con = (HttpURLConnection) msiEndpoint.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Metadata", "true");
 
        if (con.getResponseCode()!=200) {
            throw new Exception("Error calling managed identity token endpoint.");
        }
 
        InputStream responseStream = con.getInputStream();
 
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(responseStream);
 
        while(!parser.isClosed()){
            JsonToken jsonToken = parser.nextToken();
 
            if(JsonToken.FIELD_NAME.equals(jsonToken)){
                String fieldName = parser.getCurrentName();
                jsonToken = parser.nextToken();
 
                if("access_token".equals(fieldName)){
                    String accesstoken = parser.getValueAsString();
                    System.out.println("Access Token: " + accesstoken.substring(0,5)+ "..." + accesstoken.substring(accesstoken.length()-5));
                    return;
                }
            }
        }
    }
}

使用 Go 取得權杖Get a token using Go

package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "net/url"
  "encoding/json"
)

type responseJson struct {
  AccessToken string `json:"access_token"`
  RefreshToken string `json:"refresh_token"`
  ExpiresIn string `json:"expires_in"`
  ExpiresOn string `json:"expires_on"`
  NotBefore string `json:"not_before"`
  Resource string `json:"resource"`
  TokenType string `json:"token_type"`
}

func main() {
    
    // Create HTTP request for a managed services for Azure resources token to access Azure Resource Manager
    var msi_endpoint *url.URL
    msi_endpoint, err := url.Parse("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01")
    if err != nil {
      fmt.Println("Error creating URL: ", err)
      return 
    }
    msi_parameters := url.Values{}
    msi_parameters.Add("resource", "https://management.azure.com/")
    msi_endpoint.RawQuery = msi_parameters.Encode()
    req, err := http.NewRequest("GET", msi_endpoint.String(), nil)
    if err != nil {
      fmt.Println("Error creating HTTP request: ", err)
      return 
    }
    req.Header.Add("Metadata", "true")

    // Call managed services for Azure resources token endpoint
    client := &http.Client{}
    resp, err := client.Do(req) 
    if err != nil{
      fmt.Println("Error calling token endpoint: ", err)
      return
    }

    // Pull out response body
    responseBytes,err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
      fmt.Println("Error reading response body : ", err)
      return
    }

    // Unmarshall response body into struct
    var r responseJson
    err = json.Unmarshal(responseBytes, &r)
    if err != nil {
      fmt.Println("Error unmarshalling the response:", err)
      return
    }

    // Print HTTP response and marshalled response body elements to console
    fmt.Println("Response status:", resp.Status)
    fmt.Println("access_token: ", r.AccessToken)
    fmt.Println("refresh_token: ", r.RefreshToken)
    fmt.Println("expires_in: ", r.ExpiresIn)
    fmt.Println("expires_on: ", r.ExpiresOn)
    fmt.Println("not_before: ", r.NotBefore)
    fmt.Println("resource: ", r.Resource)
    fmt.Println("token_type: ", r.TokenType)
}

使用 Azure PowerShell 取得權杖Get a token using Azure PowerShell

下列範例示範如何從 PowerShell 用戶端使用 Azure 資源受控識別 REST 端點來執行下列動作:The following example demonstrates how to use the managed identities for Azure resources REST endpoint from a PowerShell client to:

  1. 取得存取權杖。Acquire an access token.
  2. 使用存取權杖來呼叫 Azure Resource Manager REST API,並取得虛擬機器的相關資訊。Use the access token to call an Azure Resource Manager REST API and get information about the VM. 請務必以您的訂用帳戶識別碼、資源群組名稱和虛擬機器名稱各別取代 <SUBSCRIPTION-ID><RESOURCE-GROUP><VM-NAME>Be sure to substitute your subscription ID, resource group name, and virtual machine name for <SUBSCRIPTION-ID>, <RESOURCE-GROUP>, and <VM-NAME>, respectively.
Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -Headers @{Metadata="true"}

說明如何對回應中的存取權杖進行剖析的範例:Example on how to parse the access token from the response:

# Get an access token for managed identities for Azure resources
$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' `
                              -Headers @{Metadata="true"}
$content =$response.Content | ConvertFrom-Json
$access_token = $content.access_token
echo "The managed identities for Azure resources access token is $access_token"

# Use the access token to get resource information for the VM
$vmInfoRest = (Invoke-WebRequest -Uri 'https://management.azure.com/subscriptions/<SUBSCRIPTION-ID>/resourceGroups/<RESOURCE-GROUP>/providers/Microsoft.Compute/virtualMachines/<VM-NAME>?api-version=2017-12-01' -Method GET -ContentType "application/json" -Headers @{ Authorization ="Bearer $access_token"}).content
echo "JSON returned from call to get VM info:"
echo $vmInfoRest

使用 CURL 取得權杖Get a token using CURL

curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true -s

說明如何對回應中的存取權杖進行剖析的範例:Example on how to parse the access token from the response:

response=$(curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true -s)
access_token=$(echo $response | python -c 'import sys, json; print (json.load(sys.stdin)["access_token"])')
echo The managed identities for Azure resources access token is $access_token

權杖快取Token caching

雖然使用中的 Azure 資源受控識別子系統 (IMDS/Azure 資源受控識別 VM 擴充功能) 會快取權杖,但仍建議在程式碼中實作權杖快取。While the managed identities for Azure resources subsystem being used (IMDS/managed identities for Azure resources VM Extension) does cache tokens, we also recommend to implement token caching in your code. 因此請為資源表示權杖到期的情節做好準備。As a result, you should prepare for scenarios where the resource indicates that the token is expired.

只有在以下情況中,才會向 Azure AD 進行線上呼叫:On-the-wire calls to Azure AD result only when:

  • 由於 Azure 資源受控識別子系統快取中沒有權杖而發生快取遺漏cache miss occurs due to no token in the managed identities for Azure resources subsystem cache
  • 快取的權杖已過期the cached token is expired

錯誤處理Error handling

Azure 資源受控識別端點會透過 HTTP 回應訊息標頭的狀態碼欄位 (如 4xx 或 5xx 錯誤) 來發出錯誤通知:The managed identities for Azure resources endpoint signals errors via the status code field of the HTTP response message header, as either 4xx or 5xx errors:

狀態碼Status Code 錯誤原因Error Reason 處理方式How To Handle
404 找不到。404 Not found. 正在更新 IMDS 端點。IMDS endpoint is updating. 使用指數輪詢重試。Retry with Expontential Backoff. 請參閱下面的指引。See guidance below.
429 要求太多。429 Too many requests. 已達到 IMDS 節流限制。IMDS Throttle limit reached. 使用指數輪詢重試。Retry with Exponential Backoff. 請參閱下面的指引。See guidance below.
要求中的 4xx 錯誤。4xx Error in request. 一個或多個要求參數不正確。One or more of the request parameters was incorrect. 請勿重試。Do not retry. 檢查錯誤詳細資料以取得更多資訊。Examine the error details for more information. 4xx 錯誤是設計階段錯誤。4xx errors are design-time errors.
來自服務的 5xx 暫時性錯誤。5xx Transient error from service. Azure 資源受控識別子系統或 Azure Active Directory 傳回了暫時性錯誤。The managed identities for Azure resources sub-system or Azure Active Directory returned a transient error. 等待至少一秒後即可安全地進行重試。It is safe to retry after waiting for at least 1 second. 如果您太快重試或重試太多次,IMDS 和/或 Azure AD 可能會傳回速率限制錯誤 (429)。If you retry too quickly or too often, IMDS and/or Azure AD may return a rate limit error (429).
timeouttimeout 正在更新 IMDS 端點。IMDS endpoint is updating. 使用指數輪詢重試。Retry with Expontential Backoff. 請參閱下面的指引。See guidance below.

如果發生錯誤,對應的 HTTP 回應主體會包含 JSON 格式的錯誤詳細資料:If an error occurs, the corresponding HTTP response body contains JSON with the error details:

元素Element 描述Description
errorerror 錯誤識別碼。Error identifier.
error_descriptionerror_description 錯誤的詳細資訊描述。Verbose description of error. 錯誤描述可以隨時變更。請勿將程式碼撰寫為會針對錯誤描述中的值建立分支。Error descriptions can change at any time. Do not write code that branches based on values in the error description.

HTTP 回應參考HTTP response reference

本節會說明可能的錯誤回應。This section documents the possible error responses. 「200 確定」狀態是成功的回應,而且存取權杖會包含在回應主體 JSON 中 (在 access_token 元素中)。A "200 OK" status is a successful response, and the access token is contained in the response body JSON, in the access_token element.

status codeStatus code 錯誤Error 錯誤說明Error Description 方案Solution
400 不正確的要求400 Bad Request invalid_resourceinvalid_resource AADSTS50001:在名為 <TENANT-ID> 的租用戶中找不到名為 <URI> 的應用程式。AADSTS50001: The application named <URI> was not found in the tenant named <TENANT-ID>. 如果租用戶的系統管理員尚未安裝此應用程式或租用戶中的任何使用者尚未同意使用此應用程式,也可能會發生此錯誤。This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. 您可能會將驗證要求傳送至錯誤的租用戶。You might have sent your authentication request to the wrong tenant.\ (僅限 Linux)(Linux only)
400 不正確的要求400 Bad Request bad_request_102bad_request_102 未指定必要的中繼資料標頭Required metadata header not specified 要求中遺漏 Metadata 要求標頭欄位,或欄位的格式不正確。Either the Metadata request header field is missing from your request, or is formatted incorrectly. 值必須指定為 true (全部小寫)。The value must be specified as true, in all lower case. 相關範例請參閱前一節 REST 中的「範例要求」。See the "Sample request" in the preceding REST section for an example.
401 未經授權401 Unauthorized unknown_sourceunknown_source 未知的來源 <URI>Unknown Source <URI> 請確認 HTTP GET 要求 URI 的格式正確。Verify that your HTTP GET request URI is formatted correctly. scheme:host/resource-path 部分必須指定為 http://localhost:50342/oauth2/tokenThe scheme:host/resource-path portion must be specified as http://localhost:50342/oauth2/token. 相關範例請參閱前一節 REST 中的「範例要求」。See the "Sample request" in the preceding REST section for an example.
invalid_requestinvalid_request 要求遺漏必要參數、包含無效參數值、多次包含某個參數或格式不正確。The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.
unauthorized_clientunauthorized_client 用戶端無權使用此方法要求存取權杖。The client is not authorized to request an access token using this method. 因為要求並未使用本機回送呼叫擴充功能,或是所在的虛擬機器沒有正確設定 Azure 資源受控識別。Caused by a request that didn’t use local loopback to call the extension, or on a VM that doesn’t have managed identities for Azure resources configured correctly. 如果您需要設定虛擬機器的協助,請參閱使用 Azure 入口網站在虛擬機器上設定 Azure 資源受控識別See Configure managed identities for Azure resources on a VM using the Azure portal if you need assistance with VM configuration.
access_deniedaccess_denied 資源擁有者或授權伺服器已拒絕要求。The resource owner or authorization server denied the request.
unsupported_response_typeunsupported_response_type 授權伺服器不支援使用此方法取得存取權杖。The authorization server does not support obtaining an access token using this method.
invalid_scopeinvalid_scope 要求的範圍無效、未知或格式不正確。The requested scope is invalid, unknown, or malformed.
500 內部伺服器錯誤500 Internal server error 未知unknown 無法從 Active 目錄擷取權杖。Failed to retrieve token from the Active directory. 如需詳細資訊,請參閱<檔案路徑> 中的記錄For details see logs in <file path> 確認已在虛擬機器上啟用 Azure 資源受控識別。Verify that managed identities for Azure resources has been enabled on the VM. 如果您需要設定虛擬機器的協助,請參閱使用 Azure 入口網站在虛擬機器上設定 Azure 資源受控識別See Configure managed identities for Azure resources on a VM using the Azure portal if you need assistance with VM configuration.

也請確認 HTTP GET 要求 URI 的格式正確,尤其是查詢字串中指定的資源 URI。Also verify that your HTTP GET request URI is formatted correctly, particularly the resource URI specified in the query string. 相關範例請參閱前一節 REST 中的「範例要求」,或請參閱支援 Azure AD 驗證的 Azure 服務,以取得服務及其各自資源識別碼的清單。See the "Sample request" in the preceding REST section for an example, or Azure services that support Azure AD authentication for a list of services and their respective resource IDs.

重試指引Retry guidance

若您收到 404、429 或 5xx 錯誤碼,建議您重試 (請參閱上方的錯誤處理)。It is recommended to retry if you receive a 404, 429, or 5xx error code (see Error handling above).

節流限制會套用至對 IMDS 端點進行的呼叫數目。Throttling limits apply to the number of calls made to the IMDS endpoint. 超過節流閾值時,IMDS 端點會在節流生效時,限制任何進一步的要求。When the throttling threshold is exceeded, IMDS endpoint limits any further requests while the throttle is in effect. 在這段期間,IMDS 端點會傳回 HTTP 狀態碼 429 (「太多要求」),且要求會失敗。During this period, the IMDS endpoint will return the HTTP status code 429 ("Too many requests"), and the requests fail.

對於重試,我們建議下列策略:For retry, we recommend the following strategy:

重試策略Retry strategy 設定Settings Values 運作方式How it works
ExponentialBackoffExponentialBackoff 重試計數Retry count
最小輪詢Min back-off
最大輪詢Max back-off
差異輪詢Delta back-off
第一個快速重試First fast retry
55
0 秒0 sec
60 秒60 sec
2 秒2 sec
falsefalse
嘗試 1 - 延遲 0 秒Attempt 1 - delay 0 sec
嘗試 2 - 延遲 ~2 秒Attempt 2 - delay ~2 sec
嘗試 3 - 延遲 ~6 秒Attempt 3 - delay ~6 sec
嘗試 4 - 延遲 ~14 秒Attempt 4 - delay ~14 sec
嘗試 5 - 延遲 ~30 秒Attempt 5 - delay ~30 sec

Azure 服務的資源識別碼Resource IDs for Azure services

關於支援 Azure AD 且經過 Azure 資源受控識別所測試的資源及其各自資源識別碼的清單,請參閱支援 Azure AD 驗證的 Azure 服務See Azure services that support Azure AD authentication for a list of resources that support Azure AD and have been tested with managed identities for Azure resources, and their respective resource IDs.

後續步驟Next steps