如何从控制台应用程序从 Azure Key Vault 检索机密

问题描述 投票:0回答:1

我已经研究了 Azure Key Vault 开发人员指南、许多相关资源和相当多的问题,但仍然获得了以 Azure.Identity.CredentialUnavailableException 开头的异常列表。来自 DefaultAzureCredential 的所有尝试都会失败。这是两行代码:

var client = new SecretClient(new Uri($"https://kv-xxx.vault.azure.net"), new DefaultAzureCredential());
var secret = client.GetSecret("xxx-api-key");

我无法使用推荐的“应用程序托管身份”。该应用程序在服务帐户上下文中的服务器上运行。最初,我的印象是所有身份验证详细信息都将完全透明地传递,就像其他资源的情况一样。我通过 Azure 门户验证该帐户具有读取机密的适当权限。

我希望这个场景的简短描述能让有人引导我走向正确的方向。感觉堆栈跟踪和手头的附加任意信息无助于找到解决方案。

总而言之,我想要的是使用从 Azure Key Vault 检索机密的服务帐户在远程计算机上执行控制台应用程序,因此我不必将此机密放入源代码或任何类型的配置文件中。我能够创建秘密并允许用户读取访问权限。 但我无法在代码中对 Key Vault 进行身份验证。

祝大家新年快乐!

authentication console-application .net-6.0 azure-keyvault
1个回答
0
投票

要检索秘密值,请创建 Azure AD/Microsoft Entra ID 应用程序:

enter image description here

要获取机密值,应用程序必须具有 Key Vault Secrets User 角色 :

转到您的 Key Vault -> 访问控制 (IAM) -> 添加 -> 添加角色分配 -> 选择 Key Vault 机密用户 -> 选择成员 -> 选择您的应用程序 -> 查看 + 分配

enter image description here

现在使用以下代码即可成功检索秘密值:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

var clientId = "ClientIDofApp";
var clientSecret = "ClientSecretofApp";
var vaultUri = new Uri("https://rukkvs.vault.azure.net/");
var tenantId = "TenantID";
var secretname = "testsecret";

var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var client = new SecretClient(vaultUri, credential);
var secret = client.GetSecret(secretname);

Console.WriteLine($"secret value for the secret {secretname} is {secret.Value.Value}");

enter image description here

  • 如果您的密钥保管库配置为 “Azure 基于角色的访问控制”,则将密钥保管库机密用户角色分配给应用程序。
  • 如果您的密钥保管库配置为“保管库访问策略”,那么您必须创建访问策略,选择秘密权限并将其分配给应用程序。
© www.soinside.com 2019 - 2024. All rights reserved.