Azure KeyVault Secret Get 抛出身份验证错误

Azure KeyVault Secret Get Throws Authentication Error

我正在设置一个 KeyVault 以从我的 .NET Azure WebApp 中删除机密并通过 CredScan,据我所知一切都已正确连接。

KeyVault 与应用存在于同一资源组中,并且具有所需的机密。应用服务在 KeyVault 的访问策略中设置了明确的读取权限。根据文档,所有正确的参数都用于在代码中创建 API 客户端。

然而,当我使用标准 API 调用来使用客户端实际访问秘密时,即

SecretClient client = new SecretClient(keyVaultURI, new DefaultAzureCredential());
string secret = client.GetSecret(secretName).Value.Value;

我收到以下错误:

DefaultAzureCredential failed to retrieve a token from the included credentials.\r\nEnvironmentCredential authentication unavailable. Environment variables are not fully configured.\r\nManagedIdentityCredential authentication unavailable, no managed identity endpoint found.\r\nSharedTokenCacheCredential authentication unavailable. Token acquisition failed for user . Ensure that you have authenticated with a developer tool that supports Azure single sign on.

我猜一定有一些我不知道的必需配置步骤或设置。

我将整个解决方案总结如下。

如果您想DefaultAzureCredential访问Azure 应用服务中的Azure 密钥保管库,您需要启用MSI 并在Azure 密钥保管库中为您的MSI 配置正确的访问策略。更多详情,请参考document

详细步骤如下。

一个。启用系统分配的 MSI

  • 向下滚动到左侧导航中的 设置 组。
  • Select 身份.
  • 系统分配选项卡中,将状态切换为开启。单击保存

b。配置访问策略

  • 在 Azure 的 “搜索资源对话框” 中搜索您的 Key Vault 传送门.
  • Select "Overview",然后单击访问策略
  • 从下拉列表中单击 "Add New"、select "Secret Management" "Configure from template"
  • 单击“Select Principal”,然后在搜索字段中输入您之前创建的 Web 应用程序 MSI 的对象 ID。 Select 结果列表中的 Web 应用程序,然后单击 "Select"
  • 点击"OK"添加新的访问策略,然后点击"Save"保存 访问策略