c# - 从 WPF 应用程序 Net Core 3.1 连接到 Azure KeyVault
问题描述
在我当前的 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 密钥保管库并进行身份验证?
解决方案
首先,设置环境变量用于Azure.Identity
创建DefaultAzureCredential()
. 所以你需要设置它们。
如果您的应用托管在 Azure 上,您可以按照此示例和此文档轻松使用托管标识DefaultAzureCredential
来访问 Azure KeyVault 。
请记住在上面第一个链接的步骤 1 中设置访问策略(它是 Azure 中的环境变量),这将授予您的服务主体/托管标识对 Key Vault 的访问权限。
但正如您所说,您的应用程序是 WPF,它很可能在本地运行(对应于托管在 Azure 上)。在这种情况下,您没有托管标识,但您仍然可以创建服务主体来访问您的 Azure KeyVault。
您可以参考此文档:适用于 .NET - 版本 4.2.0-beta.5 的 Azure Key Vault 机密客户端库。
创建服务主体后,最重要的事情和我之前提到的一样:设置访问策略(您将在此步骤中看到环境变量)。您可以像这样在 Powershell 中设置它:
az keyvault set-policy --name <your-key-vault-name> --spn $Env:AZURE_CLIENT_ID --secret-permissions backup delete get list set
然后创建 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");
推荐阅读
- c++ - 如何为扫雷 C++ 程序声明一个工作变量?
- c++ - 用 C++ 代码编译 lex/yacc 的困难
- vba - 根据时间输入创建时间范围
- c# - 子弹冲击力未按预期工作
- r - 调解 R 包 p 值:获得更多有效数字的解决方法?
- angular - 如何使用 Jest/Spectator 在 Angular 中测试路由/导航?
- liquid - FetchXML 查询在流动模板中不起作用
- javascript - HTML表单输入类型文件用javascript预选值
- caching - Apache2.4 +AEM+HEAD
- sql - 使用 SQL Server 存储过程时出现 VBScript 错误“需要对象”