无法使Azure KeyVault配置提供程序正常工作

时间:2018-01-02 16:36:48

标签: c# azure .net-core azure-keyvault

我尝试在.Net Core控制台应用程序中设置Azure KeyVault配置提供程序。 我已按照this文档进行操作。

但它没有取得秘密。我可以使用KeyVaultClient来获取它。

这是完整的代码:

class Program
{
    public static IConfigurationRoot Configuration { get; set; }

    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

        var secretUri = $"{Configuration["Vault"]}secrets/testSecret/4438b47c28cc413f9434bcb2d3c7d7ca";

        var keyVault = new KeyVaultClient(async (string authority, string resource, string scope) => {
            var authContext = new AuthenticationContext(authority);
            var credential = new ClientCredential(Configuration["ClientId"], Configuration["ClientSecret"]);
            var token = await authContext.AcquireTokenAsync(resource, credential);

            return token.AccessToken;
        });

        var result1 = keyVault.GetSecretAsync(secretUri).Result.Value;

        builder.AddAzureKeyVault(
            Configuration["Vault"],
            Configuration["ClientId"],
            Configuration["ClientSecret"]);

        var result2 = Configuration["testSecret"];
    }
}

result1从keyvault获取值,但result2null

不确定这里出了什么问题。

1 个答案:

答案 0 :(得分:3)

我也遵循你提到的documentation。如果我在添加keyVault后重新构建构建器,我可以获得值。

 builder.AddAzureKeyVault(
            Configuration["Vault"],
            Configuration["ClientId"],
            Configuration["ClientSecret"]);
Configuration = builder.Build();
var result2 = Configuration["testSecret"];

测试结果

enter image description here