IC Improve Code Recipes

Recipe 6.4 · C#

User Secrets, Environment Variables and Azure Key Vault

Problem

Developers need real credentials to run the app locally, so they paste them into appsettings.json and hope to remember not to commit them. Servers get the same values by hand. Rotating a password means editing files on every server and in every developer's working copy.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

JSON
{
  "PaymentApi": {
    "BaseUrl": "https://api.example.com",
    "ApiKey": "sk_live_REPLACE_ME_but_nobody_ever_does"
  }
}

The improved recipe

Keep each secret's name in code and its value outside the repository: user secrets on developer machines, environment variables on simple hosts, and Azure Key Vault in the cloud or wherever you can reach it.

On a developer machine:

PowerShell
dotnet user-secrets init
dotnet user-secrets set "PaymentApi:ApiKey" "dev-key-from-test-portal"

$cs = "Server=localhost;Database=AppDb;" +
    "Integrated Security=true;TrustServerCertificate=true"
dotnet user-secrets set "ConnectionStrings:AppDb" $cs

On a server or in a container, with environment variables:

PowerShell
$env:PaymentApi__ApiKey = "value-from-your-secret-store"
$env:ConnectionStrings__AppDb = "Server=sql01;Database=AppDb;..."
# For a service or app pool, set them at machine or process level.

In Azure or with a vault, add Key Vault as one more configuration source. This uses the Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity packages.

C#
using System;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;

namespace ImproveCode.Configuration;

/// <summary>Loads only secrets named "{prefix}--...", so several
/// apps can share one vault. "Billing--PaymentApi--ApiKey"
/// becomes the key "PaymentApi:ApiKey".</summary>
public sealed class PrefixKeyVaultSecretManager(string prefix)
    : KeyVaultSecretManager
{
    private readonly string _prefix = prefix + "--";

    public override bool Load(SecretProperties secret) =>
        secret.Enabled == true &&
        secret.Name.StartsWith(
            _prefix, StringComparison.OrdinalIgnoreCase);

    public override string GetKey(KeyVaultSecret secret) =>
        secret.Name[_prefix.Length..]
            .Replace("--", ConfigurationPath.KeyDelimiter);
}

public static class KeyVaultSetup
{
    public static WebApplicationBuilder AddKeyVaultSecrets(
        this WebApplicationBuilder builder, string prefix)
    {
        string? vaultUri = builder.Configuration["KeyVault:Uri"];
        if (string.IsNullOrWhiteSpace(vaultUri))
        {
            return builder; // e.g. local development
        }

        builder.Configuration.AddAzureKeyVault(
            new Uri(vaultUri),
            new DefaultAzureCredential(),
            new AzureKeyVaultConfigurationOptions
            {
                Manager = new PrefixKeyVaultSecretManager(prefix),
                ReloadInterval = TimeSpan.FromMinutes(30)
            });

        return builder;
    }
}

Usage in Program.cs:

C#
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.AddKeyVaultSecrets(prefix: "Billing");
builder.Services.AddPaymentApiOptions();   // Recipe 6.2

How it works

All three mechanisms are configuration sources, so the code from Recipes 6.1 and 6.2 doesn't change. PaymentApiOptions.ApiKey is bound from whichever source supplies PaymentApi:ApiKey. The JSON file can keep the key with an empty value as documentation, or leave it out entirely.

User secrets live in a JSON file in your user profile (under %APPDATA%\Microsoft\UserSecrets\<id> on Windows), keyed by the UserSecretsId that dotnet user-secrets init adds to the project file. They are outside the repository, so they can't be committed, and the host loads them automatically when the environment is Development. They are not encrypted; they are a convenience for development, not a vault.

Environment variables use __ in place of :. They are the lowest common denominator: IIS application pools, Windows services, containers, Azure App Service settings and CI pipelines can all set them, and they never touch the file system of the app.

Key Vault stores secrets centrally with access control, auditing and versioning. Secret names can't contain colons, so the convention is --, which the manager converts back. The prefix lets one vault serve several applications without each one loading the others' secrets. DefaultAzureCredential tries managed identity in Azure, then the developer's Visual Studio or Azure CLI sign-in locally, so there is no credential to protect for reaching the vault itself. ReloadInterval refreshes values periodically, so a rotated secret reaches IOptionsMonitor consumers without a restart.

Variations and pitfalls

  • In production, DefaultAzureCredential probes several credential types before finding the right one, which slows startup and can pick an unexpected identity. Use ManagedIdentityCredential there, and DefaultAzureCredential only for development.
  • Load Key Vault after the JSON files (as here) so vault values override them. The host still adds environment variables and command-line arguments ahead of it, so a vault value wins over an environment variable with the same key. Pick one home per secret.
  • On-premises servers without Azure can use the Windows Credential Manager, DPAPI-protected files, or HashiCorp Vault. The principle is the same: a configuration source that reads from outside the repository.
  • Access policies should give each app read access to its own secrets only, and nobody's laptop should be able to read production values.
  • Never log configuration values at startup. Log the names of the sources (Recipe 6.3) instead.

On .NET Framework

.NET Framework 4.7.1 added configuration builders for web.config and app.config. The Microsoft.Configuration.ConfigurationBuilders.Environment, .UserSecrets and .Azure packages replace appSettings and connectionStrings values at run time from environment variables, a user-secrets file or Key Vault, so a legacy app can drop its hard-coded passwords without code changes.