reggaemahn
reggaemahn

Reputation: 6668

Azure KeyVault Configuration Provider reload values on change

I'm using Azure Key Vault Configuration Provider to read some secrets at app startup. The secrets however keep rotating throughout the day and I want to be able to reload the new values when this rotation happens.

What I'm talking about is similar to the reloadOnChange api

.ConfigureAppConfiguration((context, config) =>
{
    config.AddJsonFile("appsettings.json", reloadOnChange: true);
})

Is this possible at all?

This is a webapi project so in practice, I could get away with manually reloading the values for every HttpRequest if that's better/more feasibe.

Upvotes: 9

Views: 8004

Answers (3)

Philip Vrazhevski
Philip Vrazhevski

Reputation: 101

Same thing as Bobby Koteski proposed, but with a newer Azure.Extensions.AspNetCore.Configuration.Secrets package, as Microsoft.Extensions.Configuration.AzureKeyVault is deprecated.

ReloadInterval is a time to wait between attempts at polling the Azure Key Vault for changes.

configurationBuilder.AddAzureKeyVault(
    new SecretClient(
        new Uri(configuration["KeyVaultBaseUrl"]),
        new ManagedIdentityCredential(configuration["UserAssignedManagedIdentityClientId"])
    ),
    new AzureKeyVaultConfigurationOptions()
    {
        ReloadInterval = TimeSpan.FromSeconds(1000)
    }
);

And a link to a source code to see how it actually works :)

Upvotes: 8

Bobby Koteski
Bobby Koteski

Reputation: 303

Using Microsoft.Extensions.Configuration.AzureKeyVault (v3) you can do the following:

configurationBuilder.AddAzureKeyVault(new AzureKeyVaultConfigurationOptions
{
    Vault = configuration["KeyVaultUrl"],
    ReloadInterval = TimeSpan.FromMinutes(10),
    Client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
       new AzureServiceTokenProvider().KeyVaultTokenCallback))
});

Now when you request for IConfiguration in your services, the KeyVault secrets will be available and refreshed based on your reload interval.

Upvotes: 17

Joey Cai
Joey Cai

Reputation: 20127

Secrets are cached until IConfigurationRoot.Reload() is called. Expired, disabled, and updated secrets in the key vault are not respected by the app until Reload is executed.

Configuration.Reload();

For more details, you could refer to this article.

Upvotes: 4

Related Questions