Introduction

In this Sample, we will see how we will handle the secrets in .Net Core web Application using Azure Key Vault.

Building the Sample

Installing the below NuGet Package

 

C#
Edit|Remove
Install-Package Microsoft.Extensions.Configuration.AzureKeyVault -Version 2.1.1
 

 

 

Description

 

As more and more applications moving into the cloud, the more and more securities that need to be handled carefully. Normally for WebApps whether it's a .NetFramework (or) .NetCore all the configuration and secrets were kept in `web.config` (or) `appsettings.json` all the connection string/ApplicationId/ApplicationSecrets/Passwords were stored in those configurations. But this should not be kept as directly in the configuration which is less secure.


So we are going to managing secrets in our .Net core Webapplication by adding the configuration as config.AzureKeyVault in the IWebHosBuilder. 

The Secrets are configured in the Azure Key Vault. You need to register your application to the Azure key vault. Once you registered you will provide the client id and client secrets and the KeyVault in the appsettings.json

  1. Vault
  2. ClientId
  3. ClientSecret

For development purpose, you can store the secrets in secrets.json

 


 

Which can be found %APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.jsons

The values of the secrets which will be in stored in azurekeyvault will be overridden in appsetting.json

 

The priority will always be 

  1. AzureKeyVault
  2. secrets.json
  3. appsetting.json

 

 

Program.cs

 

C#
Edit|Remove
public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
             WebHost.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((context, config) =>
                 {
                     var builtConfig = config.Build();

                     config.AddAzureKeyVault(
                         $"https://{builtConfig["Vault"]}.vault.azure.net/",
                         builtConfig["ClientId"],
                         builtConfig["ClientSecret"]);
                 })
                 .UseStartup<Startup>();
    }

appsettings.json

C#
Edit|Remove
{ 
  "Logging": { 
    "LogLevel": { 
      "Default""Warning" 
    } 
  }, 
  "AllowedHosts""*", 
  "myConnectionString""For development Set in User secrets(Local),For Production,Set is Azure KeyVault,", 
  "Vault""myKeyVault", 
  "ClientId""xxxxx-xxx-xxx-xxx-xxxx", 
  "ClientSecret""xxxxxxx=" 
}
 

Source Code Files

More Information

You can find all the detailed Article here