使用受控識別進行驗證

適用於:所有 API 管理 層

使用 authentication-managed-identity 原則來透過受控識別向後端服務進行驗證。 基本上,此原則使用受控識別,從 Microsoft Entra ID 取得存取權杖,以存取指定的資源。 成功取得權杖之後,此原則會在 Authorization 標頭中使用 Bearer 配置來設定權杖的值。 APIM 會快取權杖,直到權杖到期為止。

系統指派的身分識別,以及使用者指派的多個身分識別中任何一個,都可用來要求權杖。 如果未提供 client-id,則採用系統指派的身分識別。 如果提供 client-id 變數,則會從 Microsoft Entra ID,為該使用者指派的身分識別要求權杖。

注意

請依照原則陳述式中提供的順序,來設定原則的元素和子元素。 深入了解如何設定或編輯 APIM 原則

原則陳述式

<authentication-managed-identity resource="resource" client-id="clientid of user-assigned identity" output-token-variable-name="token-variable" ignore-error="true|false"/>  

屬性

屬性 描述 是必要欄位 預設
resource 字串。 Microsoft Entra ID 中目標 Web API (受保護的資源) 的應用程式識別碼。 允許使用原則運算式。 Yes N/A
client-id 字串。 Microsoft Entra ID 中使用者指派身分識別的用戶端識別碼。 不允許使用原則運算式。 No 系統指派的身分識別
output-token-variable-name 字串。 內容變數的名稱,此變數將會以類型 string 的物件形式接收權杖值。 不允許使用原則運算式。 No N/A
ignore-error 布林值。 如果設定為 true,即使未取得存取權杖,原則管線仍會繼續執行。 No false

使用方式

範例

使用受控識別向後端服務進行驗證

<authentication-managed-identity resource="https://graph.microsoft.com"/> 
<authentication-managed-identity resource="https://management.azure.com/"/> <!--Azure Resource Manager-->
<authentication-managed-identity resource="https://vault.azure.net"/> <!--Azure Key Vault-->
<authentication-managed-identity resource="https://servicebus.azure.net/"/> <!--Azure Service Bus-->
<authentication-managed-identity resource="https://eventhubs.azure.net/"/> <!--Azure Event Hub-->
<authentication-managed-identity resource="https://storage.azure.com/"/> <!--Azure Blob Storage-->
<authentication-managed-identity resource="https://database.windows.net/"/> <!--Azure SQL-->
<authentication-managed-identity resource="AD_application_id"/> <!--Application (client) ID of your own Azure AD Application-->

使用受控識別並手動設定標頭

<authentication-managed-identity resource="AD_application_id"
   output-token-variable-name="msi-access-token" ignore-error="false" /> <!--Application (client) ID of your own Azure AD Application-->
<set-header name="Authorization" exists-action="override">
   <value>@("Bearer " + (string)context.Variables["msi-access-token"])</value>
</set-header>

在 send-request 原則中使用受控識別

<send-request mode="new" timeout="20" ignore-error="false">
    <set-url>https://example.com/</set-url>
    <set-method>GET</set-method>
    <authentication-managed-identity resource="ResourceID"/>
</send-request>

如需使用原則的詳細資訊,請參閱: