IC Improve Code Recipes

Recipe 6.4 · Python

User Secrets, Environment Variables and Azure Key Vault

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

Usage in Program.cs:

Requirements: Python 3.12+. Install: pip install azure-identity azure-keyvault-secrets · Needs at run time: an Azure Key Vault and an Azure sign-in. The module loads without them; calling the code does not work without them.

Python Loading prefixed Azure Key Vault secrets into configuration (p131_r6_4_prefixed_azure_key_vault_secrets.py)
"""Loading prefixed Azure Key Vault secrets into configuration

Source: ImproveCode, Chapter 6, Recipe 6.4 "User Secrets, Environment Variables and Azure Key Vault"
Section: The improved recipe
Book page: 131-132  -- original C# listing
Converted from C# to Python.
azure-identity's DefaultAzureCredential and azure-keyvault-secrets' SecretClient replace
the AddAzureKeyVault configuration provider; secrets are merged into a flat "A:B" config
dict, and a reload_interval is returned for the caller to schedule (no built-in reload).
"""

from __future__ import annotations

from datetime import timedelta

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import KeyVaultSecret, SecretClient, SecretProperties

KEY_DELIMITER = ":"


class PrefixKeyVaultSecretManager:
    """Loads only secrets named "{prefix}--...", so several
    apps can share one vault. "Billing--PaymentApi--ApiKey"
    becomes the key "PaymentApi:ApiKey"."""

    def __init__(self, prefix: str) -> None:
        self._prefix = prefix + "--"

    def load(self, secret: SecretProperties) -> bool:
        return (secret.enabled is True
                and (secret.name or "").lower().startswith(self._prefix.lower()))

    def get_key(self, secret: KeyVaultSecret) -> str:
        return (secret.name or "")[len(self._prefix):].replace("--", KEY_DELIMITER)


RELOAD_INTERVAL = timedelta(minutes=30)


def add_key_vault_secrets(config: dict[str, str], prefix: str) -> dict[str, str]:
    vault_uri = config.get("KeyVault:Uri")
    if not vault_uri or not vault_uri.strip():
        return config  # e.g. local development

    manager = PrefixKeyVaultSecretManager(prefix)
    client = SecretClient(vault_url=vault_uri, credential=DefaultAzureCredential())

    for props in client.list_properties_of_secrets():
        if manager.load(props):
            secret = client.get_secret(props.name)  # type: ignore[arg-type]
            config[manager.get_key(secret)] = secret.value or ""

    return config

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Startup: load Key Vault secrets then register validated options (p132_r6_4_startup_key_vault_and_options.py)
"""Startup: load Key Vault secrets then register validated options

Source: ImproveCode, Chapter 6, Recipe 6.4 "User Secrets, Environment Variables and Azure Key Vault"
Section: The improved recipe
Book page: 132  -- original C# listing
Converted from C# to Python.
add_key_vault_secrets is from p131_r6_4_prefixed_azure_key_vault_secrets.py and
load_payment_api_options from p125_r6_2_validated_payment_api_options.py (Recipe 6.2).
"""

from __future__ import annotations

from typing import Any, Callable


def build(
    config: dict[str, str],
    add_key_vault_secrets: Callable[..., dict[str, str]],
    load_payment_api_options: Callable[[], Any],
) -> Any:
    add_key_vault_secrets(config, prefix="Billing")
    return load_payment_api_options()   # 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.