使用托管标识进行身份验证

通过 authentication-managed-identity 策略使用托管标识向后端服务进行身份验证。 此策略实质上是使用托管标识从 Microsoft Entra ID 获取访问令牌以访问指定资源。 成功获取令牌后,策略将使用 Bearer 方案在 Authorization 标头中设置令牌的值。 API 管理会缓存令牌,直到其过期。

系统分配的标识和多个用户分配的标识都可用来请求令牌。 如果未提供 client-id,则采用系统分配的标识。 如果提供了 client-id 变量,则会从 Microsoft Entra ID 为该用户分配标识请求令牌。

注意

按照策略声明中提供的顺序设置策略的元素和子元素。 详细了解如何设置或编辑 API 管理策略

策略语句

<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(受保护的资源)的应用程序 ID。 允许使用策略表达式。 空值
client-id 字符串。 Microsoft Entra ID 中用户分配标识的客户端 ID。 不允许使用策略表达式。 系统分配的标识
output-token-variable-name 字符串。 上下文变量的名称,它将令牌值接收为类型为 string 的对象。 不允许使用策略表达式。 空值
ignore-error 布尔值。 如果设置为 true,即使未获得访问令牌,策略管道也会继续执行。 false

使用情况

示例

使用托管标识向后端服务进行身份验证

<authentication-managed-identity resource="https://microsoftgraph.chinacloudapi.cn"/> 
<authentication-managed-identity resource="https://management.chinacloudapi.cn/"/> <!--Azure Resource Manager-->
<authentication-managed-identity resource="https://vault.azure.cn"/> <!--Azure Key Vault-->
<authentication-managed-identity resource="https://servicebus.chinacloudapi.cn/"/> <!--Azure Service Bus-->
<authentication-managed-identity resource="https://eventhubs.chinacloudapi.cn/"/> <!--Azure Event Hub-->
<authentication-managed-identity resource="https://storage.azure.com/"/> <!--Azure Blob Storage-->
<authentication-managed-identity resource="https://database.chinacloudapi.cn/"/> <!--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 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>

后续步骤

有关使用策略的详细信息,请参阅: