从密钥库向 Azure APIM 添加证书

发布时间:2021-03-01 16:23

在 Azure API 管理中,有一个选项可以通过引用密钥库中的证书从门户添加证书:

Azure APIM adding certificate from keyvault screenshot

是否可以使用 az cli、powershell 或 terraform 执行此操作?

我浏览了文档,我发现的唯一示例(包括 Terraform)似乎涉及上传证书字节的副本,而不是引用它。我希望能够引用它,以便 APIM 在证书更改时自动重新加载。

回答1

您可以使用以下命令直接从 API Management 调用 Azure CLI REST API:

az rest --method put --url "https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/certificates/{certificateId}?api-version=2020-06-01-preview" --body @body.json

其中 this describes the URI parameters 和文件 body.json 将反映 request body defined here

{
  "properties": {
    "keyVault": {
      "identityClientId": "{SystemAssignedIdentity or UserAssignedIdentity Client Id which will be used to access key vault secret.}",
      "secretIdentifier" : "{Key vault secret identifier for fetching secret. Providing a versioned secret will prevent auto-refresh. This requires Api Management service to be configured with aka.ms/apimmsi}"
    }
  }
}
回答2

我已经阅读了官方 Azure CLI 和 Azure PowerShell APIM 参考,正如您所说,它们没有提供从 keyVault 设置证书参考的方法。但我认为我们可以从 keyVault 导出 .pfx 并将其导入 APIM 作为解决方法。只需尝试 PS 命令:

$apimName = ""
$apimSresourceGroup = ""
$keyVaultName = "" 
$certName = ""
$password = ""

#export pfx
$cert = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $certName
$secret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $cert.Name 
$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($secretByte, "", "Exportable,PersistKeySet")
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$pfxFileByte = $x509Cert.Export($type, $password)

#import to APIM 
$apim_context = New-AzApiManagementContext -ResourceGroupName $apimSresourceGroup -ServiceName $apimName
New-AzApiManagementCertificate -Context $apim_context -CertificateId 'testcert' -PfxBytes $pfxFileByte -PfxPassword $password 

结果: enter image description here enter image description here