简体   繁体   中英

Fetching KeyVault values through App Configuration

I'd like to fetch both App Configuration and KeyVault values directly from IConfiguration. This is from a console application in.Net 7

Program.cs:

var host = Host.CreateDefaultBuilder()
    .ConfigureLogging(a => a.AddConsole())
    .ConfigureHostConfiguration(config => config.AddEnvironmentVariables())
    .ConfigureAppConfiguration(config =>
    {
        config.ConfigureKeyVault();
    })
    .ConfigureServices((context, services) =>
    {
        var env = context.HostingEnvironment;
        var startUp = new Startup(env);
        startUp.ConfigureServices(services);
        startUp.ConfigureConsoleMethods(services);
                
        _serviceProvider = services.BuildServiceProvider(true); 
    })
    .Build();

Extension Method:

public static void ConfigureKeyVault(this IConfigurationBuilder config)
{
    var settings = config.Build();

    var appConfigConnString = settings.GetConnectionString("AppConfig");
    var keyVaultEndpoint = settings.GetValue<string>("KeyVault:Endpoint");
    var kvOptions = new DefaultAzureCredentialOptions { ManagedIdentityClientId = settings.GetValue<string>("KeyVault:ClientId") };

    config.AddAzureAppConfiguration(options =>
   {
        options.Connect(appConfigConnString);
        options.ConfigureKeyVault(x => x.SetCredential(new DefaultAzureCredential(kvOptions)));
    });
}

With this setup, I can fetch my KeyVault keys like this:

services.AddScoped<IApiFactory, ApiFactory>(x =>
{
    var keyVault = x.GetRequiredService<IKeyVaultService>();
                
    return new ApiFactory(
        keyVault.GetSecret("SomeObj:ClientId"),
        keyVault.GetSecret("SomeObj:ClientSecret"));
});

But I would rather get my key's using IConfiguration, like this:

services.AddScoped<IApiFactory, ApiFactory>(x =>
{        
    return new ApiFactory(
        this.Configuration.GetValue<string>("SomeObj:ClientId"),
        this.Configuration.GetValue<string>("SomeObj:ClientSecret"));
});

Question

How can I fetch my KeyVault values from IConfiguration?

If you set up a key vault reference in Azure App Configuration, the secret retrieved from the key vault should be accessible from IConfiguration .

  • Make sure the key name (eg "SomeObj:ClientId") is the one that you set in Azure App Configuration instead of the secret name you set in Key Vault.
  • Make sure the configuration is built before you attempt to access it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM