使用 MSI 连接到 Azure Vault

标签 c .net azure azure-security shared-secret

我正在尝试使用 MSI 从控制台应用程序连接到我的 Azure 保管库

对于此保管库,我已将我的用户添加为选定原则
我用来连接的代码是

var azureServiceTokenProvider = new AzureServiceTokenProvider();

var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

var secret = await keyVaultClient.GetSecretAsync("https://<vaultname>.vault.azure.net/secrets/<SecretName>").ConfigureAwait(false);

我收到以下异常

Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connectionstring: [No connection string specified], Resource: https://vault.azure.net, Authority

enter image description here

最佳答案

  1. 在虚拟机下的配置边栏选项卡中启用托管服务身份。

Enable MSI in the virtual machine configuration blade

  • 搜索NameOfYourVM服务主体并将其添加到访问策略下的 key 保管库。添加 key / secret /证书权限。
  • Add Service Principal to Key Vault

  • 在您的 Azure VM 上运行控制台应用。
  • class Program
    {
        // Target C# 7.1+ in your .csproj for async Main
        static async Task Main()
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
    
            var keyVaultClient = new KeyVaultClient(
                  new KeyVaultClient.AuthenticationCallback(
                        azureServiceTokenProvider.KeyVaultTokenCallback));
    
            var secret = await keyVaultClient.GetSecretAsync(
                  "https://VAULT-NAME.vault.azure.net/secrets/SECRET-NAME");
    
            Console.WriteLine(secret.Value);
            Console.ReadLine();
        }
    }
    

    Console output

    要在本地运行,请创建您自己的 Azure AD 应用程序注册(Web 应用程序/Web API 类型以使其成为 secret 客户端),将其添加到 Key Vault 并在获取访问 token 时使用其 client_id 和 client_secret —
    https://learn.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application#gettoken

    Varun评论中提到,现在有一种更好的方法可以在本地运行时获取访问 token ,而无需公开服务主体 -

    https://learn.microsoft.com/en-us/azure/key-vault/service-to-service-authentication#local-development-authentication

    关于使用 MSI 连接到 Azure Vault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027391/

    相关文章:

    c - 如何在 C 中使用正则表达式?

    .net - 我如何在 UltraWinGrid 中设置自定义字体?

    python - 片键和 Azure CosmosDB for MongoDB API

    c# - 为什么 FileSystemWatcher 在创建文件时引发 Changed 事件?

    c# - 使用反射捕获方法状态

    Azure Web作业无法连接到存储帐户

    azure - Powershell 函数 -WhatIf 用于没有 -WhatIf 支持的 cmdlet?

    c - MPI(异步)循环迭代

    c - 我如何在父子进程之间共享内存,以便在它们死亡时自动释放内存

    C:[错误]链表快速排序