如何从 Azure 应用服务访问密钥保管库

How to access key vault from azure app service

我使用以下方法连接到我的代码中的密钥保管库:

public static class ConfigurationBuilderExtension
{
    public static IConfigurationBuilder AddKeyVaultconfiguration(this IConfigurationBuilder builder)
    {
        var config = builder.Build();

        string name = config["KeyVault:Name"];
        string clientId = config["KeyVault:ClientId"];
        string clientSecret = config["KeyVault:ClientSecret"];

        Verify.NotNullOrEmpty(name, nameof(name));
        Verify.NotNullOrEmpty(name, nameof(clientId));
        Verify.NotNullOrEmpty(name, nameof(clientSecret));

        builder.AddAzureKeyVault($"https://{name}.vault.azure.net/", clientId, clientSecret);

        return builder;
    }
}

为了 运行 在本地,我只是将用户机密添加到项目中:

{
  "KeyVault": {
    "Name": "brajzorekeyvault",
    "ClientId": "xxxx",
    "ClientSecret": "xxxx"
  }
}

这在本地有效。

但是,当我将其发布到 Azure 中的应用服务时,如何使用这种方法?我必须以某种方式注入名称、clientId 和 clientSecret?但我不知道这样做的最佳实践方法是什么?我应该在 Azure devops 中创建一个包含这些值的变量组,然后在管道中使用它们吗?

您应该使用托管身份访问 Web 应用程序内的密钥保管库,以避免必须注入密码。参见 this tutorial

对于本地开发,您可以 link VS 中的一个帐户,该帐户将用于针对密钥保管库进行身份验证。参见 the docs

使用托管身份是最佳实践,事实上,如果没有使用托管身份的警告,您将看不到任何关于使用客户端密码进行连接的官方文档。