Skip to content

7.4 — Key Vault and Secrets Manager Providers

← Roadmap · Section: 7. Configuration and Options Prev: 7.3 Environment variables and User Secrets · Next: 7.5 The IConfiguration API

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

A secret store is a managed service that holds credentials, controls who can read them, and logs every access. Azure Key Vault and AWS Secrets Manager are the two you will meet.

  • They plug in as configuration providers, so your application code does not change — you still read config["Payments:ApiKey"].
  • The real win is not hiding the secret but auditing, rotation and access control.
  • The identity problem — how does the app authenticate to the vault? — is solved by managed identity, so there is no bootstrap secret.

Definitions

Term What it is What it means
Secret store a managed service Stores credentials with access control, auditing and versioning.
Azure Key Vault a secret store Microsoft's. Holds secrets, keys and certificates.
AWS Secrets Manager a secret store Amazon's equivalent. Adds built-in rotation.
Managed identity an Azure feature An identity attached to the running resource, so no credential is needed to authenticate.
DefaultAzureCredential a class Tries several authentication methods in order — managed identity in Azure, your developer login locally.
AddAzureKeyVault a method Registers Key Vault as a configuration provider.
Double dash a naming convention -- in a Key Vault secret name becomes : in the configuration key.
Rotation a security practice Replacing a credential periodically, so a leaked one has a limited life.
Bootstrap problem a chicken-and-egg issue Needing a secret in order to fetch your secrets. Managed identity solves it.
Audit log a record Who read which secret, and when. The main reason to use a vault.

The concept

What a vault actually buys you

The obvious answer is "it keeps secrets out of source control" — but environment variables do that too (7.3), and they are simpler.

The real reasons are the ones environment variables cannot provide:

Access control per secret. The payments service can read the Stripe key; the reporting service cannot. With environment variables, anyone who can read the deployment manifest or exec into the container sees everything.

An audit log. You can answer "who read the production database password, and when?" That question comes up during incidents and in compliance reviews, and environment variables have no answer to it.

Rotation without redeployment. Change the secret in the vault and applications pick it up — either on restart or on a refresh interval. With environment variables, rotating means editing manifests and redeploying every consumer.

Versioning. A bad rotation can be rolled back.

A picture: a hotel safe versus a drawer. Both keep things out of sight. The safe also records every opening, restricts who has the code, and lets you change the code without emptying the drawer.

⚠️ The bootstrap problem

If secrets live in a vault, how does the application authenticate to the vault? Storing a vault credential in configuration recreates exactly the problem you were solving.

Managed identity solves it. The cloud platform attaches an identity to the running resource — the App Service, the VM, the Kubernetes pod — and the platform itself vouches for it. There is no credential to store.

That is the piece that makes the whole approach work, and it is worth being able to explain, because it is the obvious objection to a vault.


How it works

The simple version — Azure Key Vault

var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsProduction())
{
    builder.Configuration.AddAzureKeyVault(
        new Uri($"https://{builder.Configuration["KeyVault:Name"]}.vault.azure.net/"),
        new DefaultAzureCredential());
}

Two details.

Added after the defaults, so it takes precedence over the JSON files (7.1). Order is precedence.

Production only. Locally you use User Secrets, so developers do not need vault access to run the application.

Reading the values needs no code change at all:

var apiKey = builder.Configuration["Payments:ApiKey"];      // may come from Key Vault

That is the point of the provider model. The application does not know or care where a setting came from.

⚠️ The naming convention

Key Vault secret names allow only alphanumerics and hyphens — no colons. So the convention is double hyphen:

Key Vault secret name Configuration key
ConnectionStrings--Default ConnectionStrings:Default
Payments--ApiKey Payments:ApiKey
Payments--Stripe--WebhookSecret Payments:Stripe:WebhookSecret

Note this is a third escape convention, after : in JSON and __ in environment variables. Mixing them up is a genuinely common mistake:

JSON / CLI args     →  Payments:ApiKey
Environment vars    →  Payments__ApiKey        (double UNDERSCORE)
Key Vault           →  Payments--ApiKey        (double HYPHEN)

How DefaultAzureCredential works

It tries authentication methods in order and uses the first that succeeds:

  1. Environment variables (a service principal, if configured)
  2. Managed identity — in Azure, this is the one that works
  3. Visual Studio / VS Code signed-in account
  4. Azure CLI (az login)
  5. Azure PowerShell

In production it lands on managed identity; on a developer machine it lands on your az login session. Same code, no configuration difference — which is why it is the recommended default.

⚠️ Because it tries several in order, failures are slow and the error is vague. A missing permission produces a long message listing every method it attempted. When diagnosing, specify the credential explicitly to get a clearer error:

new ManagedIdentityCredential(clientId: "...")     // one method, one clear failure

AWS Secrets Manager

The same shape, different package:

builder.Configuration.AddSecretsManager(configurator: options =>
{
    options.SecretFilter = entry => entry.Name.StartsWith("myapp/");
    options.KeyGenerator = (entry, key) => key.Replace("myapp/", string.Empty)
                                              .Replace("__", ":");
    options.PollingInterval = TimeSpan.FromMinutes(15);
});

Authentication uses the IAM role attached to the EC2 instance, ECS task or Lambda — the same idea as managed identity.

AWS Secrets Manager has built-in rotation with Lambda functions, including managed rotation for RDS credentials. Key Vault supports rotation but you wire the automation yourself.

The deeper detail — refresh and caching

⚠️ By default, secrets are read once at startup. A rotated secret is not picked up until the application restarts.

For Key Vault you can enable periodic reloading:

builder.Configuration.AddAzureKeyVault(
    vaultUri,
    new DefaultAzureCredential(),
    new AzureKeyVaultConfigurationOptions
    {
        ReloadInterval = TimeSpan.FromHours(1)
    });

⚠️ Do not set this too low. Key Vault is rate-limited and charged per operation, and every instance of your application polls independently. Fifty pods on a one-minute interval is 72,000 requests a day for values that change monthly.

⚠️ And reloading configuration does not update everything. Services holding IOptions<T> captured the value at startup — you need IOptionsMonitor<T> for it to change (7.6), and things like a DbContext connection string are fixed when the context is configured (7.9).

Restarting on rotation is often simpler and more predictable than chasing live refresh through every layer.


Code

A realistic production setup with a fallback and clear failure:

var builder = WebApplication.CreateBuilder(args);

if (!builder.Environment.IsDevelopment())
{
    var vaultName = builder.Configuration["KeyVault:Name"]
        ?? throw new InvalidOperationException(
            "KeyVault:Name must be configured outside Development.");

    builder.Configuration.AddAzureKeyVault(
        new Uri($"https://{vaultName}.vault.azure.net/"),
        new DefaultAzureCredential(),
        new AzureKeyVaultConfigurationOptions
        {
            ReloadInterval = TimeSpan.FromHours(6)
        });
}

// Validate the secrets we need, at startup rather than at first use
builder.Services
    .AddOptions<PaymentOptions>()
    .Bind(builder.Configuration.GetSection("Payments"))
    .ValidateDataAnnotations()
    .ValidateOnStart();                    // fail at boot, not on the first payment

var app = builder.Build();

ValidateOnStart matters here. Without it, a missing secret produces a 500 on the first customer payment; with it, the deployment fails and never receives traffic (7.8).

Setting the secrets

# Azure — note the DOUBLE HYPHEN
az keyvault secret set --vault-name myapp-kv \
    --name "Payments--ApiKey" --value "sk_live_..."

az keyvault secret set --vault-name myapp-kv \
    --name "ConnectionStrings--Default" --value "Server=prod;..."

# Grant the app's managed identity read access — and ONLY read
az role assignment create \
    --role "Key Vault Secrets User" \
    --assignee <managed-identity-object-id> \
    --scope /subscriptions/.../vaults/myapp-kv

⚠️ "Key Vault Secrets User" is read-only, which is what an application needs. Granting a broader role like "Key Vault Administrator" means a compromised application can also write and delete secrets. Least privilege matters more here than almost anywhere else.


Interview questions

Q: Why use Key Vault rather than environment variables?

Environment variables keep secrets out of source control, which is the minimum, but a vault adds three things they cannot. Access control per secret, so one service can read the payment key and another cannot — whereas any process that can read the environment sees everything. An audit log, so you can answer who read the production database password and when, which comes up during incidents and compliance reviews. And rotation without redeployment, since changing the value in the vault does not require editing manifests and redeploying every consumer.

Q: How does the application authenticate to the vault without a secret?

Managed identity. The cloud platform attaches an identity to the running resource — the App Service, VM or pod — and vouches for it, so there is no credential to store. That solves the bootstrap problem, which is the obvious objection to using a vault: if secrets live in the vault, what protects the vault credential? DefaultAzureCredential tries several methods in order and lands on managed identity in Azure and your az login session locally, so the same code works in both without configuration differences. AWS uses IAM roles for the same purpose.

Q: What is the naming convention for Key Vault secrets?

Double hyphens, because secret names allow only alphanumerics and hyphens — no colons. So Payments--ApiKey becomes the configuration key Payments:ApiKey. It is worth being careful because that is the third escape convention in the same system: colons in JSON and command-line arguments, double underscores in environment variables, and double hyphens in Key Vault. Mixing them up produces a setting that is silently absent rather than an error.

Q: Do applications pick up a rotated secret automatically?

Not by default — secrets are read once at startup, so a rotation needs a restart. You can enable a reload interval on the Key Vault provider, but two caveats apply. The interval should not be short, because every instance polls independently and Key Vault is rate-limited and charged per operation. And reloading configuration does not automatically flow everywhere: a service holding IOptions<T> captured its value at startup, so you need IOptionsMonitor<T>, and some things like a configured connection string are fixed when the DbContext is set up. In practice restarting on rotation is often simpler and more predictable.


Traps ⚠️

  • Key Vault uses --, environment variables use __, JSON uses :. Three conventions, easily confused.
  • Secrets are read once at startup unless you configure a reload interval.
  • A short reload interval hits rate limits and costs, multiplied by every instance.
  • Reloading configuration does not update IOptions<T> — that snapshot was taken at startup.
  • DefaultAzureCredential failures are slow and vague, because it tries several methods. Specify one explicitly when diagnosing.
  • Granting more than read access means a compromised app can delete your secrets.
  • Adding the provider before the defaults means JSON files override the vault.
  • Local developers should not need vault access. Use User Secrets in Development.


Sources