通过 REST 将证书从 Azure Key Vault 添加到 Azure App Service API

Add certificate from Azure Key Vault to Azure App Service via REST API

我正在尝试通过 REST API(在 PowerShell 中)将私有自签名证书添加到 Azure 应用服务(如底部屏幕截图所示)。我调用 API 如下:

$certBody = @{
  name = "InfoServiceTAKeyVaultDev"
  location = "West Europe"
  properties = @{
    keyVaultId = "/subscriptions/<subscriptionId>/resourceGroups/BzInfoServiceTADEV/providers/Microsoft.KeyVault/vaults/BzKVInfoServiceTADev"
    keyVaultSecretName = "InfoServiceTAKeyVaultCert"
  }
}
Invoke-RestMethod `
  -Method Put `
  -Uri ("https://management.azure.com/subscriptions/<subscriptionId>" +
        "/resourceGroups/BzInformatieServiceResourceGroupDEV" +
        "/providers/Microsoft.Web/certificates" +
        "/InfoServiceTAKeyVaultDev" +
        "?api-version=2016-03-01") `
  -Headers @{ Authorization = ("Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSU...")
              "Content-Type" = "application/json" } `
  -Body ($certBody | ConvertTo-Json -Compress -Depth 3)

结果是一条错误信息:The service does not have access to '/subscriptions/<subscriptionId>/resourcegroups/bzinfoservicetadev/providers/microsoft.keyvault/vaults/bzkvinfoservicetadev' Key Vault. Please make sure that you have granted necessary permissions to the service to perform the request operation.

在此上下文中,谁是无权访问此 Key Vault 的“服务”?我已经发现 some posts 声称我应该将服务主体 abfa0a7c-a6b6-4736-8310-5855508787cd 添加到我的 Key Vault 访问策略中,但这没有任何效果。

所需最终结果的屏幕截图:

更新:我已经启用高级访问策略启用对 Azure 资源管理器的访问以进行模板部署。这也不行。

您需要添加 Enable access to Azure Resource Manager for template deployment 高级访问策略。

您不是直接将证书添加到 webapp,而是告诉 webapp 证书所在的位置。 Web 应用程序依靠资源管理器实际去收集证书并将其安装到 Web 应用程序中。

Key Vault 确实有广泛的审计日志记录,可以启用它来了解什么试图访问机密,从而使这些问题更容易调试。

事实证明,@tim-scriv 的评论非常有帮助。我必须将以下主体添加到 Key Vault 访问策略:Microsoft Azure App Service(对象 ID:3ed082e0-d6c4-4071-ac9e-61363535a0a3)。获得 secrets 的权限就足够了。

我遇到了上述问题并按照这篇文章解决了它 https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-certificate-from-key-vault;

默认情况下,'Microsoft.Azure.WebSites' 资源提供程序 (RP) 无权访问模板中指定的 Key Vault,因此您需要在部署模板之前通过执行以下 PowerShell 命令对其进行授权:

Login-AzureRmAccount Set-AzureRmContext -SubscriptionId AZURE_SUBSCRIPTION_ID Set-AzureRmKeyVaultAccessPolicy -VaultName KEY_VAULT_NAME -ServicePrincipalName abfa0a7c-a6b6-4736-8310-5855508787cd -PermissionsToSecrets get

ServicePrincipalName 参数表示用户租户中的 Microsoft.Azure.WebSites RP,并且对于所有 Azure 订阅都将保持不变。这是一次性手术。正确配置 Key Vault 后,您可以使用它部署任意数量的证书,而无需再次执行这些 PowerShell 命令。

添加 Microsoft Azure App Service 主体以 GET 访问 KeyVault 也为我解决了同样的问题。

在我的例子中,我尝试使用 azurerm_template_deployment 命令通过 Terraform 执行 ARM 模板,以将 SSL 证书添加到 Azure Web 应用服务,然后将证书绑定到 URL。