【问题标题】:Connect to Azure KeyVault from WPF app Net Core 3.1从 WPF 应用程序 Net Core 3.1 连接到 Azure KeyVault
【发布时间】:2021-08-03 20:47:04
【问题描述】:

在我当前的 Net Core 3.1 WPF 项目中,我希望用户能够连接到 Azure 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 key vault 并进行身份验证?

【问题讨论】:

  • 嗨,你有机会看看我的回答吗?

标签: c# wpf asp.net-core azure-keyvault azure-identity


【解决方案1】:

首先,设置环境变量是为了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");

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多