Uso de identidades administradas en Azure API ManagementUse managed identities in Azure API Management

En este artículo se muestra cómo crear una identidad administrada para una instancia de servicio de API Management y cómo acceder a otros recursos.This article shows you how to create a managed identity for an API Management service instance and how to access other resources. Una identidad administrada generada por Azure Active Directory (Azure AD) permite a la instancia de API Management acceder de forma fácil y segura a otros recursos protegidos de Azure AD, como 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. Esta identidad está administrada por Azure y no requiere que aprovisione o rote los secretos.This identity is managed by Azure and does not require you to provision or rotate any secrets. Para más información sobre las identidades administradas, consulte el artículo sobre qué son las identidades administradas para recursos de Azure.For more information about managed identities, see What is managed identities for Azure resources.

Creación de una identidad administrada para una instancia de API ManagementCreate a managed identity for an API Management instance

Uso de Azure PortalUsing the Azure portal

Para configurar una identidad administrada en el portal, primero tendrá que crear una instancia de API Management como lo hace normalmente y, a continuación, habilitar la característica.To set up a managed identity in the portal, you will first create an API Management instance as normal and then enable the feature.

  1. Cree una instancia de API Management en el portal como lo haría normalmente.Create an API Management instance in the portal as you normally would. Navegue hasta el portal.Navigate to it in the portal.
  2. Seleccione Identidades de servicio administradas.Select Managed service identities.
  3. Cambie Registrar en Azure Active Directory a Activado.Switch Register with Azure Active Directory to On. Haga clic en Guardar.Click Save.

Habilitación de MSI

Uso de la plantilla de Azure Resource ManagerUsing the Azure Resource Manager template

Puede crear una instancia de API Management con una identidad mediante la inclusión de la siguiente propiedad en la definición de recursos:You can create an API Management instance with an identity by including the following property in the resource definition:

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

Esto indica a Azure que debe crear y administrar la identidad para la instancia de API Management.This tells Azure to create and manage the identity for your API Management instance.

Por ejemplo, una plantilla de Azure Resource Manager completa podría tener el aspecto siguiente: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": "2017-03-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"
        }
    }]
}

Uso de la identidad de servicio administrada para acceder a otros recursosUse the managed service identity to access other resources

Nota

Actualmente, las identidades administradas se pueden utilizar para obtener certificados de Azure Key Vault para los nombres de dominio personalizados de API Management.Currently, managed identities can be used to obtain certificates from Azure Key Vault for API Management custom domain names. Pronto se admitirán más escenarios.More scenarios will be supported soon.

Obtención de un certificado en Azure Key VaultObtain a certificate from Azure Key Vault

PrerequisitesPrerequisites

  1. El almacén de claves que contiene los certificados pfx debe estar en la misma suscripción de Azure y el mismo grupo de recursos que el servicio API Management.The Key Vault containing the pfx certificate must be in the same Azure subscription and the same Resource Group as the API Management service. Se trata de un requisito de la plantilla de Azure Resource Manager.This is a requirement of the Azure Resource Manager template.
  2. El tipo de contenido del secreto debe ser application/x-pkcs12.The Content Type of the secret must be application/x-pkcs12. Puede usar el siguiente script para cargar el certificado:You can use the following script to upload the certificate:
$pfxFilePath = "PFX_CERTIFICATE_FILE_PATH" # Change this path 
$pwd = "PFX_CERTIFICATE_PASSWORD" # Change this password 
$flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable 
$collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection 
$collection.Import($pfxFilePath, $pwd, $flag) 
$pkcs12ContentType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12 
$clearBytes = $collection.Export($pkcs12ContentType) 
$fileContentEncoded = [System.Convert]::ToBase64String($clearBytes) 
$secret = ConvertTo-SecureString -String $fileContentEncoded -AsPlainText –Force 
$secretContentType = 'application/x-pkcs12' 
Set-AzureKeyVaultSecret -VaultName KEY_VAULT_NAME -Name KEY_VAULT_SECRET_NAME -SecretValue $Secret -ContentType $secretContentType

Importante

Si no se proporciona la versión del objeto del certificado, API Management obtiene automáticamente la versión más reciente del certificado una vez cargado a Key Vault.If the object version of the certificate is not provided, API Management will automatically obtain the newer version of the certificate after it is uploaded to Key Vault.

En el ejemplo siguiente se muestra una plantilla de Azure Resource Manager que contiene los siguientes pasos:The following example shows an Azure Resource Manager template that contains the following steps:

  1. Creación de una instancia de API Management con una identidad administrada.Create an API Management instance with a managed identity.
  2. Actualización de las directivas de acceso de una instancia de Azure Key Vault y permiso para que la instancia de API Management obtenga secretos de ella.Update the access policies of an Azure Key Vault instance and allow the API Management instance to obtain secrets from it.
  3. Actualización de la instancia de API Management estableciendo un nombre de dominio personalizado mediante un certificado de la instancia de Key Vault.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 service"
            }
        },
        "skuCount": {
            "type": "int",
            "defaultValue": 1,
            "metadata": {
                "description": "The instance size of this API Management service."
            }
        },
        "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 KeyVault certificate. https://contoso.vault.azure.net/secrets/contosogatewaycertificate."
            }
        }
    },
    "variables": {
        "apiManagementServiceName": "[concat('apiservice', uniqueString(resourceGroup().id))]",
        "apimServiceIdentityResourceId": "[concat(resourceId('Microsoft.ApiManagement/service', variables('apiManagementServiceName')),'/providers/Microsoft.ManagedIdentity/Identities/default')]"
    },
    "resources": [{
        "apiVersion": "2017-03-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')]"}
            }
        }
    }]
}

Pasos siguientesNext steps

Obtenga más información sobre las identidades administradas para recursos de Azure:Learn more about managed identities for Azure resources: