0

I've some .NET 9 applications that use appsettings.json to load settings, but some of them contain sensitive data, and I would like to resolve them as I do for Azure functions via @Microsoft.KeyVault directive.

I've found this link, but it applies to web.config, I don't know how and if I've to set the binder as it's told.

My settings are the following:

  "KeyVaultUrl": "https://mykeyvault-dev.vault.azure.net/",
  "AzureConfig": {
    "Url": "https://myappconfig.azconfig.io",
    "RefreshInterval": "00:02:00"
  },
  "ElasticPassword":"@Microsoft.KeyVault(VaultName=mykeyvault-dev;SecretName=elastic-search-password)",

Now, if this is in Azure Functions, the correct value from the vault is resolved automatically even when I run from Visual Studio inside, when using

var item = _configuration.GetValue<string>("something");

In a web application (I would say the one that has var builder=WebApplication.CreateBuilder()), it does not seem to work.

The code I'm trying to use is

public static async Task Main(string[] args)
{
     var builder = WebApplication.CreateBuilder(args);

     // Get Key Vault details
     var configurationTmp = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
     var tmp = configurationTmp.Build();

     string appConfigurationUrl = tmp.GetValue<string>("RedactionConfig:AzureConfig:Url");
     TimeSpan refreshTimespan = tmp.GetValue<TimeSpan>("RedactionConfig:AzureConfig:RefreshInterval");

     var configuration = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
         .AddAzureKeyVault(
             new Uri("https://myVault.azure.net/"),
             new DefaultAzureCredential(),
             new AzureKeyVaultConfigurationOptions
             {
               
                 ReloadInterval = TimeSpan.FromMinutes(5)
             })
         .AddEnvironmentVariables()
         .AddAzureAppConfiguration(delegate (AzureAppConfigurationOptions opt)
         {
             var tokenCredential = new DefaultAzureCredential();

             opt.Connect(new Uri(appConfigurationUrl), tokenCredential).ConfigureKeyVault(
                 delegate (AzureAppConfigurationKeyVaultOptions kv)
                 {
                     kv.SetCredential(tokenCredential);
                 });
         })
         .Build();

     builder.Configuration.AddConfiguration(configuration);
}

When I try to resolve, I get as value

@Microsoft.KeyVault(VaultName=kv-as-shared-dev;SecretName=elastic-search-password)

Can anyone help me with this?

Thanks

7
  • But on local deoloyment what should I put? Commented May 19 at 3:19
  • Will check from my end and explain you in detail. Commented May 19 at 3:32
  • You are using Function app? or a WebApp ? Commented May 19 at 3:33
  • Web app ... on function app it works Commented May 19 at 3:38
  • If you want them to work locally, try to store them in Azure App configuration = > key Vault reference and retrieve them Commented May 19 at 3:41

1 Answer 1

0

@Microsoft.KeyVault works only for the deployed Application in Production environment.

enter image description here

But on local deployment what should I put?

Locally you can store the secrets in Environment Variables and retrieve the value using,

var secVal= Environment.GetEnvironmentVariable("ElasticPassword"); 

Another altearnative,

To work with Key Vault references in local, you can reference them from the Azure App Configuration.

  • First create a secret in the Key Vault.

enter image description here

  • Create a Key vault reference in the Azure App Configuration.

enter image description here

  • Map the created Key vault secret with the Key Vault reference in App Config => Configuration explorer.

enter image description here

  • In code, install Azure.Identity and Microsoft.Extensions.Configuration.AzureAppConfiguration NuGet packages.

My appsettings.json file:

 "ConnectionStrings": {
   "AppConfig": "Endpoint=https://appconfigmay.azconfig.io;Id=RPuc;Secret=****"
 }
  • Copy the above connection string from Azure App config => Access settings.

My Program.cs file:

using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);

var Conn = builder.Configuration.GetConnectionString("AppConfig");
builder.Host.ConfigureAppConfiguration(configBuilder =>
{
    configBuilder.AddAzureAppConfiguration(options =>
    {
        options.Connect(Conn)          
            .ConfigureKeyVault(kv =>
            {
                kv.SetCredential(new DefaultAzureCredential());
            });
    });
});
  • You can retrieve the secret from the configuration.
var secret = builder.Configuration["ElasticPassword"];

enter image description hereNOTE:- Key Name has to be same as the one which we created in Configuration explorer => Key Vault reference.

Output:
enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Ok but you confirm that when running from localhost those are not resolved (thing that instead happens when running an azure function). As I've read till now those settings should be put in usersecret file correct?
If you want reference to work as @Microsoft.Keyvault.. then set in user secrets locally and in environment variables application settings in production.Then in both the environments your code will work if you retrieve the value using GetEnvironment variable.
Key Vault references are not resolved automatically when running an ASP.NET Core app locally. In Azure Functions, the runtime handles the Key Vault references in App Configuration even during local development, it is a built-in feature of the Azure Functions runtime. In ASP.NET Core you must explicitly configure Azure App Configuration and Key Vault integration using code and even then, it only works if you authenticate it using DefaultAzureCredential() or by adding .ConfigureKeyVault(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.