从 WPF 应用程序 Net Core 3.1 连接到 Azure KeyVault

问题描述

在我当前的 Net Core 3.1 WPF 项目中,我希望用户能够连接到 Azure Key Vault。 我设置了一个 Key Vault,其中设置了一些访问策略或用户

在文档中,我阅读了很多有关使用 SecretClient(new Uri(_keyvaultUrl),new DefaultAzureCredential()); 使用环境变量设置与密钥保管库的连接的信息。我不明白的是环境变量在这里有什么用处,因为它们仅限于设置它们的单台机器。 上面的代码在我的代码中返回一个 Null 对象错误

Azure.Identity.CredentialUnavailableException: 'DefaultAzureCredential Failed to retrieve a token from the included credentials.
- EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
- ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.
Status: 400 (Bad Request)

是否有一种直接的方法可以让我使用客户端机密、应用程序 ID,然后使用 Azure 身份库连接并使用 Azure 密钥保管库进行身份验证?

解决方法

首先,设置环境变量是为了让Azure.Identity用来创建DefaultAzureCredential()。所以你需要设置它们。

如果您的应用托管在 Azure 上,您可以通过 this sample 和此 document 轻松使用托管标识和 DefaultAzureCredential 访问 Azure KeyVault。

请记住在上面第一个链接的第 1 步中设置访问策略(在 Azure 中是环境变量),这将授予您的服务主体/托管标识访问权限密钥保管库。

但正如您所说,您的应用程序是 WPF,它很可能在本地运行(对应于托管在 Azure 上)。在这种情况下,您没有托管标识,但您仍然可以创建服务主体来访问您的 Azure KeyVault。

您可以参考此文档:Azure Key Vault secret client library for .NET - Version 4.2.0-beta.5

创建服务主体后,最重要的事情和我之前提到的一样:设置访问策略(您将在此步骤中看到环境变量)。您可以像这样在 Powershell 中设置它:

az keyvault set-policy --name <your-key-vault-name> --spn $Env:AZURE_CLIENT_ID --secret-permissions backup delete get list set

然后 create SecretClient 访问 KeyVault:

// Create a new secret client using the default credential from Azure.Identity using environment variables previously set,// including AZURE_CLIENT_ID,AZURE_CLIENT_SECRET,and AZURE_TENANT_ID.
var client = new SecretClient(vaultUri: new Uri(keyVaultUrl),credential: new DefaultAzureCredential());

// Create a new secret using the secret client.
KeyVaultSecret secret = client.SetSecret("secret-name","secret-value");

// Retrieve a secret using the secret client.
secret = client.GetSecret("secret-name");