Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 832
reggaemahn Avatar asked Jun 29 '19 01:06

reggaemahn


3 Answers

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.

like image 147
Bobby Koteski Avatar answered Oct 13 '22 02:10

Bobby Koteski


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.

like image 44
Joey Cai Avatar answered Oct 13 '22 00:10

Joey Cai


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 :)

like image 2
Philip Vrazhevski Avatar answered Oct 13 '22 00:10

Philip Vrazhevski