Author : HASSAN MD TAREQ

App Secrets in aspnet core

Social login providers assign Application Id and Application Secret tokens during the registration process. The exact token names vary by provider. These tokens represent the credentials your app uses to access their API. The tokens constitute the “secrets” that can be linked to your app configuration with the help of Secret Manager. Secret Manager is a more secure alternative to storing the tokens in a configuration file, such as appsettings.json.

User Secrets in Development

secrets.json

{
  "Foo": {
    "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true",
    "ApiKey": "12345"
  }
}

Accessing User Secrets

User secrets can be retrieved via the Configuration API:

public class Startup
{
    public IConfiguration Configuration { get; }
	
    private string _apiKey = null;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }


    public void ConfigureServices(IServiceCollection services)
    {
        _apiKey = Configuration["Foo:ApiKey"];
    }

    public void Configure(IApplicationBuilder app)
    {
        // use _apiKey here if needed
    }
}

See

Configuring Azure App Services for Azure KeyVault

Following setting is for activating Managed Identity in Azure App Services

Azure App Services Configuration for Azure KeyVault with Managed Identity Step 1

Azure App Services Configuration for Azure KeyVault with Managed Identity Step 2

Azure App Services Configuration for Azure KeyVault with Managed Identity Step 3

Using Azure KeyVault in Production

When using (Azure App Services) managed identity for KeyVault, then all you need to do:

Then app will use secrets:

Notes:

Installation

Install-Package Microsoft.Extensions.Configuration.AzureKeyVault

appsettings.json

{
  "AzureKeyVaultName": "hovermind-blazor-demo-vault",
  
    "...": { ... },
}

Program.cs

public class Program
{
	public static void Main(string[] args)
	{
		CreateHostBuilder(args).Build().Run();
	}

	public static IHostBuilder CreateHostBuilder(string[] args) =>
		Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) =>
		{
			if (context.HostingEnvironment.IsDevelopment())
			{ return; }

			var builtConfig = config.Build();

			config.AddAzureKeyVault($"https://{builtConfig["AzureKeyVaultName"]}.vault.azure.net/");
		})
		.ConfigureWebHostDefaults(webBuilder =>
		{
			webBuilder.UseStartup<Startup>();
		});
}

The above configuration does following (behind the scene):

//Authentication
var tokenSvc = new AzureServiceTokenProvider();

//Key Vault Client
var keyVaultClient = new KeyVaultClient(new
KeyVaultClient.AuthenticationCallback(tokenSvc.KeyVaultTokenCallback));

//Add Configuration Provider
config.AddAzureKeyVault("https://your-vault-name.vault.azure.net/", keyVaultClient, new DefaultKeyVaultSecretManager());

Accessing KeyVault Secrets in Program class

appsettings.json

{
  "KeyVaultBaseUrl": "",
}

Program.cs

namespace Hovermind.HoverApp
{
    public class Program
    {

        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, configBuilder) =>
             {
                 var Configuration = configBuilder.Build();

                 var isProduction = context.HostingEnvironment.IsProduction();
                 if (isProduction)
                 {
                     var keyVaultUrl = Configuration["KeyVaultBaseUrl"];
					 
                     configBuilder.AddAzureKeyVault(keyVaultUrl);

                     Configuration = configBuilder.Build();  // KeyVault secrets are added to Configuration
					 
                     var fooSecret = Configuration["FooSecretKey"];

                     if (!string.IsNullOrEmpty(fooSecret))
                     {
                        // Use fooSecret here
                     }
                 }
                 else
                 {
                    // Development-time settings
                 }
             })
             .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
             .UseSerilog();
    }
}

```

Testing Azure KeyVault using Azure CLI