Configuring an Azure Key Vault

    From a security perspective, it's always a good solution to store your application secrets (such as a connection string and others keys) in an Azure Key Vault. This article tells you how to configure your application so that it's ready to use a Key Vault

    Installing the package

    Before you begin, you need to install the Azure.Extensions.AspNetCore.Configuration.Secrets and the Azure.Identity NuGet packages. There are two approaches to installing the packages:

    1. Use your favorite IDE and open up the NuGet Package Manager to search and install the packages
    2. Use the command line to install the package

    Installing through command line

    Navigate to your project folder, which is the folder that contains your .csproj file. Now use the following 'dotnet add package' command to install the package:

    dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
    dotnet add package Azure.Identity

    Configuration

    The next step is to add the Azure Key Vault endpoint to the 'appsettings.json' file.

    {
      "AzureKeyVaultEndpoint": "https://{your-key-vault-name}.vault.azure.net",
    }

    After adding the Key Vault endpoint you have to update the CreateHostBuilder method which you can find in the Program.cs class.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(x => x.ClearProviders())
            .ConfigureAppConfiguration((context, config) =>
            {
                var settings = config.Build();
                var keyVaultEndpoint = settings["AzureKeyVaultEndpoint"];
                if (!string.IsNullOrWhiteSpace(keyVaultEndpoint))
                {
                    if (!string.IsNullOrWhiteSpace(keyVaultEndpoint) && Uri.TryCreate(keyVaultEndpoint, UriKind.Absolute, out var validUri))
                    {
                        config.AddAzureKeyVault(validUri, new DefaultAzureCredential());
                    }
                }
            })
            .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
    

    Authentication

    There are several ways to access the Azure Key Vault. It is important that the user you are logging in with has access to the Key Vault. You can assign roles using the Azure Portal.

    1. Navigate to your Key Vault.
    2. Select Access Control.
    3. Select Add -> Add role assignment.
    4. Select the preferred role.
    5. Search for the user.
    6. Click review + assign

    Local Developement

    1. Sign in to Visual Studio using the credentials that can access the Key Vault.
    2. Use Azure CLI to store your preferred account into the credential cache.

    Staging/Production

    1. Managed identities for Azure resources
    2. X.509 certificate for non-Azure-hosted apps