Dan Beaulieu
Dan Beaulieu

Reputation: 19954

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?

Upvotes: 1

Views: 931

Answers (1)

Zhenlan Wang
Zhenlan Wang

Reputation: 1533

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 (e.g. "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.

Upvotes: 1

Related Questions