Azure Key Vault:部署时无法从 kv 获取证书

Azure Key Vault: unable to get a cert from kv when deployed

我有一个网络作业从 Azure Key Vault 服务获取证书,在本地我没有问题 accessing/retrieving 这个来自 kv 的证书。但是,当部署此 webjob 时,出现此错误:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
   at Microsoft.Ambassadors.Infrastructure.KeyVaultService.<GetCertificateAsync>d__7.MoveNext() in C:\Source\Repos\Xbox.Ambassadors\Microsoft.Ambassadors.Azure\Microsoft.Ambassadors.Infrastructure\KeyVaultService.cs:line 0

我已经使用 AAD 注册了该应用程序(托管此 Web 作业的地方),并且它具有对 kv space 的只读访问权限。我发现了一些相关的(我认为..?)与此相关的帖子:

"An internal error occurred." when loading pfx file with X509Certificate2

X509Certificate Constructor Exception

但我不确定这是否是我可以做的事情...?如果有人可以提供帮助,那就太好了!谢谢 :D

我看到人们遇到的一个非常常见的问题与权限有关。确保代表您的 Web 作业的应用程序(服务主体)在密钥保管库访问策略中具有足够的权限,因为我没有看到您在问题中提及任何有关访问策略的内容。

步骤 -

  1. 转到您的密钥保管库访问策略 -
  2. 添加新政策
  3. Select 你的负责人(代表网络工作的应用程序)。至少授予密钥、机密和证书的获取权限
  4. 点击确定
  5. 策略 blade 完成后,单击顶部的 "save" 按钮。这是遗漏的常见步骤,政策永远不会保存。

查看此 SO post 了解多种实现方法。虽然那只是谈论秘密,所以你在添加策略时在复选框中 select 的权限会有所不同。

如果问题仍未解决,请 post 更详细的代码以从保险库访问证书,如果您的异常堆栈跟踪比您已经共享的更进一步,请将其也包括在内。

我遇到了同样的问题,只是我正在部署到 Azure Web 应用程序。我通过添加 X509KeyStorageFlags.

修复了它
SecretBundle secretBundle = await keyVaultClient.GetSecretAsync(_keyVaultOptions.IdentitySigningCredentialUri);
_signingCredential = new X509Certificate2(Convert.FromBase64String(secretBundle.Value), string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);