在 Azure API 管理中使用托管标识Use managed identities in Azure API Management

本文说明如何创建 Azure API 管理实例的托管标识以及如何访问其他资源。This article shows you how to create a managed identity for an Azure API Management instance and how to access other resources. 借助 Azure Active Directory (Azure AD) 生成的托管标识,API 管理实例可以轻松、安全访问其他受 Azure AD 保护的资源(如 Azure Key Vault)。A managed identity generated by Azure Active Directory (Azure AD) allows your API Management instance to easily and securely access other Azure AD-protected resources, such as Azure Key Vault. Azure 管理此标识,因此无需预配或轮换任何机密。Azure manages this identity, so you don't have to provision or rotate any secrets. 有关托管标识的详细信息,请参阅什么是 Azure 资源托管标识?For more information about managed identities, see What are managed identities for Azure resources?.

可以向 API 管理实例授予两种类型的标识:You can grant two types of identities to an API Management instance:

  • 系统分配的标识与你的服务绑定,如果删除服务,标识也会被删除。A system-assigned identity is tied to your service and is deleted if your service is deleted. 服务只能有一个系统分配的标识。The service can have only one system-assigned identity.
  • 用户分配的标识是可以分配给服务的独立 Azure 资源。A user-assigned identity is a standalone Azure resource that can be assigned to your service. 服务可以有多个用户分配的标识。The service can have multiple user-assigned identities.

创建系统分配的托管标识Create a system-assigned managed identity

Azure 门户Azure portal

若要在 Azure 门户中设置托管标识,需先创建 API 管理实例,然后启用该功能。To set up a managed identity in the Azure portal, you'll first create an API Management instance and then enable the feature.

  1. 按常规在门户中创建 API 管理实例。Create an API Management instance in the portal as you normally would. 在门户中浏览到它。Browse to it in the portal.

  2. 选择“托管标识”。Select Managed identities.

  3. 在“系统分配”选项卡中,将“状态”切换为“启用” 。On the System assigned tab, switch Status to On. 选择“保存” 。Select Save.

    用于启用系统分配的托管标识的选项

Azure PowerShellAzure PowerShell

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

以下步骤将指导你完成使用 Azure PowerShell 创建 API 管理实例并为其分配标识的操作。The following steps walk you through creating an API Management instance and assigning it an identity by using Azure PowerShell.

  1. 如果需要,请按照 Azure PowerShell 指南中的说明安装 Azure PowerShell。If needed, install Azure PowerShell by using the instructions in the Azure PowerShell guide. 然后运行 Connect-AzAccount 以创建与 Azure 的连接。Then run Connect-AzAccount to create a connection with Azure.

  2. 使用以下代码创建实例。Use the following code to create the instance. 有关如何将 Azure PowerShell 与 API 管理实例配合使用的更多示例,请参阅 API 管理 PowerShell 示例For more examples of how to use Azure PowerShell with an API Management instance, see API Management PowerShell samples.

    # Create a resource group.
    New-AzResourceGroup -Name $resourceGroupName -Location $location
    
    # Create an API Management Consumption Sku service.
    New-AzApiManagement -ResourceGroupName $resourceGroupName -Name consumptionskuservice -Location $location -Sku Consumption -Organization contoso -AdminEmail contoso@contoso.com -SystemAssignedIdentity
    
  3. 更新现有实例以创建标识:Update an existing instance to create the identity:

    # Get an API Management instance
    $apimService = Get-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apiManagementName
    
    # Update an API Management instance
    Set-AzApiManagement -InputObject $apimService -SystemAssignedIdentity
    

Azure Resource Manager 模板Azure Resource Manager template

在资源定义中包括以下属性,可以创建具有标识的 API 管理实例:You can create an API Management instance with an identity by including the following property in the resource definition:

"identity" : {
    "type" : "SystemAssigned"
}

此属性将告知 Azure 为 API 管理实例创建和管理标识。This property tells Azure to create and manage the identity for your API Management instance.

例如,完整的 Azure 资源管理器模板可能如下所示:For example, a complete Azure Resource Manager template might look like the following:

{
    "$schema": "https://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
    "contentVersion": "0.9.0.0",
    "resources": [{
        "apiVersion": "2019-01-01",
        "name": "contoso",
        "type": "Microsoft.ApiManagement/service",
        "location": "[resourceGroup().location]",
        "tags": {},
        "sku": {
            "name": "Developer",
            "capacity": "1"
        },
        "properties": {
            "publisherEmail": "admin@contoso.com",
            "publisherName": "Contoso"
        },
        "identity": {
            "type": "systemAssigned"
        }
    }]
}

创建实例后,它具有以下附加属性:When the instance is created, it has the following additional properties:

"identity": {
    "type": "SystemAssigned",
    "tenantId": "<TENANTID>",
    "principalId": "<PRINCIPALID>"
}

tenantId 属性标识该标识所属的 Azure AD 租户。The tenantId property identifies what Azure AD tenant the identity belongs to. principalId 属性是实例的新标识的唯一标识符。The principalId property is a unique identifier for the instance's new identity. 在 Azure AD 中,服务主体的名称与你为 API 管理实例提供的名称相同。Within Azure AD, the service principal has the same name that you gave to your API Management instance.

备注

API 管理实例可以同时具有系统分配的标识和用户分配的标识。An API Management instance can have both system-assigned and user-assigned identities at the same time. 在这种情况下,type 属性将为 SystemAssigned,UserAssignedIn this case, the type property would be SystemAssigned,UserAssigned.

支持的方案Supported scenarios

从 Azure 密钥保管库获取 API 管理实例的自定义 TLS/SSL 证书Obtain a custom TLS/SSL certificate for the API Management instance from Azure Key Vault

可以使用 API 管理实例的系统分配标识来检索存储在 Azure 密钥保管库中的自定义 TLS/SSL 证书。You can use the system-assigned identity of an API Management instance to retrieve custom TLS/SSL certificates stored in Azure Key Vault. 然后,可以将这些证书分配给 API 管理实例中的自定义域。You can then assign these certificates to custom domains in the API Management instance. 请记住以下注意事项:Keep these considerations in mind:

  • 机密的内容类型必须是 application/x-pkcs12。The content type of the secret must be application/x-pkcs12.
  • 使用包含机密的密钥保管库证书机密终结点。Use the Key Vault certificate secret endpoint, which contains the secret.

重要

如果未提供证书的对象版本,在将证书的较新版本上传到密钥保管库后的四小时内,API 管理将自动获取该版本。If you don't provide the object version of the certificate, API Management will automatically obtain the newer version of the certificate within four hours after it's updated in Key Vault.

以下示例显示包含以下步骤的 Azure 资源管理器模板:The following example shows an Azure Resource Manager template that contains the following steps:

  1. 创建含托管标识的 API 管理实例。Create an API Management instance with a managed identity.
  2. 更新 Azure Key Vault 实例的访问策略,并允许 API 管理实例从中获取机密。Update the access policies of an Azure Key Vault instance and allow the API Management instance to obtain secrets from it.
  3. 通过 Key Vault 实例中的证书设置自定义域名来更新 API 管理实例。Update the API Management instance by setting a custom domain name through a certificate from the Key Vault instance.
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "publisherEmail": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "The email address of the owner of the service"
            }
        },
        "publisherName": {
            "type": "string",
            "defaultValue": "Contoso",
            "minLength": 1,
            "metadata": {
                "description": "The name of the owner of the service"
            }
        },
        "sku": {
            "type": "string",
            "allowedValues": ["Developer",
            "Standard",
            "Premium"],
            "defaultValue": "Developer",
            "metadata": {
                "description": "The pricing tier of this API Management instance"
            }
        },
        "skuCount": {
            "type": "int",
            "defaultValue": 1,
            "metadata": {
                "description": "The instance size of this API Management instance."
            }
        },
        "keyVaultName": {
            "type": "string",
            "metadata": {
                "description": "Name of the vault"
            }
        },
        "proxyCustomHostname1": {
            "type": "string",
            "metadata": {
                "description": "Proxy Custom hostname."
            }
        },
        "keyVaultIdToCertificate": {
            "type": "string",
            "metadata": {
                "description": "Reference to the Key Vault certificate. https://contoso.vault.azure.cn/secrets/contosogatewaycertificate."
            }
        }
    },
    "variables": {
        "apiManagementServiceName": "[concat('apiservice', uniqueString(resourceGroup().id))]",
        "apimServiceIdentityResourceId": "[concat(resourceId('Microsoft.ApiManagement/service', variables('apiManagementServiceName')),'/providers/Microsoft.ManagedIdentity/Identities/default')]"
    },
    "resources": [{
        "apiVersion": "2019-01-01",
        "name": "[variables('apiManagementServiceName')]",
        "type": "Microsoft.ApiManagement/service",
        "location": "[resourceGroup().location]",
        "tags": {
        },
        "sku": {
            "name": "[parameters('sku')]",
            "capacity": "[parameters('skuCount')]"
        },
        "properties": {
            "publisherEmail": "[parameters('publisherEmail')]",
            "publisherName": "[parameters('publisherName')]"
        },
        "identity": {
            "type": "systemAssigned"
        }
    },
    {
        "type": "Microsoft.KeyVault/vaults/accessPolicies",
        "name": "[concat(parameters('keyVaultName'), '/add')]",
        "apiVersion": "2015-06-01",
        "dependsOn": [
            "[resourceId('Microsoft.ApiManagement/service', variables('apiManagementServiceName'))]"
        ],
        "properties": {
            "accessPolicies": [{
                "tenantId": "[reference(variables('apimServiceIdentityResourceId'), '2015-08-31-PREVIEW').tenantId]",
                "objectId": "[reference(variables('apimServiceIdentityResourceId'), '2015-08-31-PREVIEW').principalId]",
                "permissions": {
                    "secrets": ["get"]
                }
            }]
        }
    },
    {
        "apiVersion": "2017-05-10",
        "name": "apimWithKeyVault",
        "type": "Microsoft.Resources/deployments",
        "dependsOn": [
        "[resourceId('Microsoft.ApiManagement/service', variables('apiManagementServiceName'))]"
        ],
        "properties": {
            "mode": "incremental",
            "templateLink": {
                "uri": "https://raw.githubusercontent.com/solankisamir/arm-templates/master/basicapim.keyvault.json",
                "contentVersion": "1.0.0.0"
            },
            "parameters": {
                "publisherEmail": { "value": "[parameters('publisherEmail')]"},
                "publisherName": { "value": "[parameters('publisherName')]"},
                "sku": { "value": "[parameters('sku')]"},
                "skuCount": { "value": "[parameters('skuCount')]"},
                "proxyCustomHostname1": {"value" : "[parameters('proxyCustomHostname1')]"},
                "keyVaultIdToCertificate": {"value" : "[parameters('keyVaultIdToCertificate')]"}
            }
        }
    }]
}

使用 API 管理标识向后端进行身份验证Authenticate to the back end by using an API Management identity

可以使用系统分配的标识通过 authentication-managed-identity 策略向后端进行身份验证。You can use the system-assigned identity to authenticate to the back end through the authentication-managed-identity policy.

创建用户分配的托管标识Create a user-assigned managed identity

备注

可以将一个 API 管理实例与最多 10 个用户分配的托管标识相关联。You can associate an API Management instance with up to 10 user-assigned managed identities.

Azure 门户Azure portal

若要在门户中设置托管标识,需先创建 API 管理实例,然后启用该功能。To set up a managed identity in the portal, you'll first create an API Management instance and then enable the feature.

  1. 按常规在门户中创建 API 管理实例。Create an API Management instance in the portal as you normally would. 在门户中浏览到它。Browse to it in the portal.

  2. 选择“托管标识”。Select Managed identities.

  3. 在“用户分配”选项卡上,选择“添加”。On the User assigned tab, select Add.

  4. 搜索之前创建的标识并选择它。Search for the identity that you created earlier and select it. 选择“添加” 。Select Add.

    用于启用用户分配的托管标识的选项

Azure PowerShellAzure PowerShell

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

以下步骤将指导你完成使用 Azure PowerShell 创建 API 管理实例并为其分配标识的操作。The following steps walk you through creating an API Management instance and assigning it an identity by using Azure PowerShell.

  1. 如果需要,请按照 Azure PowerShell 指南中的说明安装 Azure PowerShell。If needed, install the Azure PowerShell by using the instructions in the Azure PowerShell guide. 然后运行 Connect-AzAccount 以创建与 Azure 的连接。Then run Connect-AzAccount to create a connection with Azure.

  2. 使用以下代码创建实例。Use the following code to create the instance. 有关如何将 Azure PowerShell 与 API 管理实例配合使用的更多示例,请参阅 API 管理 PowerShell 示例For more examples of how to use Azure PowerShell with an API Management instance, see API Management PowerShell samples.

    # Create a resource group.
    New-AzResourceGroup -Name $resourceGroupName -Location $location
    
    # Create a user-assigned identity. This requires installation of the "Az.ManagedServiceIdentity" module.
    $userAssignedIdentity = New-AzUserAssignedIdentity -Name $userAssignedIdentityName -ResourceGroupName $resourceGroupName
    
    # Create an API Management Consumption Sku service.
    $userIdentities = @($userAssignedIdentity.Id)
    
    New-AzApiManagement -ResourceGroupName $resourceGroupName -Location $location -Name $apiManagementName -Organization contoso -AdminEmail admin@contoso.com -Sku Consumption -UserAssignedIdentity $userIdentities
    
  3. 更新现有服务以向服务分配标识:Update an existing service to assign an identity to the service:

    # Get an API Management instance
    $apimService = Get-AzApiManagement -ResourceGroupName $resourceGroupName -Name $apiManagementName
    
    # Create a user-assigned identity. This requires installation of the "Az.ManagedServiceIdentity" module.
    $userAssignedIdentity = New-AzUserAssignedIdentity -Name $userAssignedIdentityName -ResourceGroupName $resourceGroupName
    
    # Update an API Management instance
    $userIdentities = @($userAssignedIdentity.Id)
    Set-AzApiManagement -InputObject $apimService -UserAssignedIdentity $userIdentities
    

Azure Resource Manager 模板Azure Resource Manager template

在资源定义中包括以下属性,可以创建具有标识的 API 管理实例:You can create an API Management instance with an identity by including the following property in the resource definition:

"identity": {
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "<RESOURCEID>": {}
    }
}

添加用户分配的类型即告知 Azure 使用为实例指定的用户分配标识。Adding the user-assigned type tells Azure to use the user-assigned identity specified for your instance.

例如,完整的 Azure 资源管理器模板可能如下所示:For example, a complete Azure Resource Manager template might look like the following:

{
    "$schema": "https://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
    "contentVersion": "0.9.0.0",
    "resources": [{
        "apiVersion": "2019-12-01",
        "name": "contoso",
        "type": "Microsoft.ApiManagement/service",
        "location": "[resourceGroup().location]",
        "tags": {},
        "sku": {
            "name": "Developer",
            "capacity": "1"
        },
        "properties": {
            "publisherEmail": "admin@contoso.com",
            "publisherName": "Contoso"
        },
        "identity": {
            "type": "UserAssigned",
             "userAssignedIdentities": {
                "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]": {}
             }
        },
        "dependsOn": [       
          "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]"
        ]
    }]
}

创建服务后,它具有以下附加属性:When the service is created, it has the following additional properties:

"identity": {
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "<RESOURCEID>": {
            "principalId": "<PRINCIPALID>",
            "clientId": "<CLIENTID>"
        }
    }
}

principalId 属性是用于 Azure AD 管理的标识的唯一标识符。The principalId property is a unique identifier for the identity that's used for Azure AD administration. clientId 属性是应用程序的新标识的唯一标识符,用于指定在运行时调用期间要使用的标识。The clientId property is a unique identifier for the application's new identity that's used for specifying which identity to use during runtime calls.

备注

API 管理实例可以同时具有系统分配的标识和用户分配的标识。An API Management instance can have both system-assigned and user-assigned identities at the same time. 在这种情况下,type 属性将为 SystemAssigned,UserAssignedIn this case, the type property would be SystemAssigned,UserAssigned.

支持的方案Supported scenarios

使用用户分配的标识向后端进行身份验证Authenticate to the back end by using a user-assigned identity

可以使用用户分配的标识通过 authentication-managed-identity 策略向后端进行身份验证。You can use the user-assigned identity to authenticate to the back end through the authentication-managed-identity policy.

删除标识Remove an identity

可以通过在门户中禁用功能或通过 Azure 资源管理器模板(和创建标识的方法相同)来删除系统分配的标识。You can remove a system-assigned identity by disabling the feature through the portal or the Azure Resource Manager template in the same way that it was created. 可以单独删除用户分配的标识。User-assigned identities can be removed individually. 若要删除所有标识,请将标识类型设置为 "None"To remove all identities, set the identity type to "None".

以这种方式删除系统分配的标识也会将它从 Azure AD 中删除。Removing a system-assigned identity in this way will also delete it from Azure AD. 删除 API 管理实例时,也将自动从 Azure AD 中删除系统分配的标识。System-assigned identities are also automatically removed from Azure AD when the API Management instance is deleted.

若要使用 Azure 资源管理器模板删除所有标识,请更新此部分:To remove all identities by using the Azure Resource Manager template, update this section:

"identity": {
    "type": "None"
}

重要

如果使用密钥保管库中的自定义 SSL 证书配置了 API 管理实例,并尝试禁用托管标识,则请求将失败。If an API Management instance is configured with a custom SSL certificate from Key Vault and you try to disable a managed identity, the request will fail.

可以通过从 Azure 密钥保管库证书切换到内联编码证书,然后禁用托管标识来取消阻止自己。You can unblock yourself by switching from an Azure Key Vault certificate to an inline encoded certificate, and then disabling the managed identity. 有关详细信息,请参阅配置自定义域名For more information, see Configure a custom domain name.

后续步骤Next steps

详细了解 Azure 资源的托管标识:Learn more about managed identities for Azure resources: