Secrets management fundamentals: what is and isn't a secret, Key Vault with managed identity and DefaultAzureCredential, the configuration provider, user secrets locally, removing secrets entirely with identity-based access, and rotation basics.
A secret is anything that grants access or proves identity: database passwords, API keys and tokens, client secrets, JWT signing keys, SAS tokens. The best secret is no secret at all: in Azure I use managed identity so the app authenticates to Azure SQL, Storage and Service Bus with Entra tokens, not stored credentials. What must remain a secret, typically a third-party API key that doesn't support Entra, goes in Azure Key Vault, read through the AddAzureKeyVault configuration provider using the app's managed identity, with Key Vault RBAC per app and a vault per environment. Locally, developers use dotnet user-secrets or their own Entra sign-in against a dev vault. Nothing goes in appsettings.json or the repo, and secret scanning blocks pushes. The trade-off: Entra and Key Vault become runtime dependencies with network hops and throttling limits, so you load at start-up, cache and reload on an interval, and automate rotation rather than doing it by hand.
"I define a secret as anything that grants access or proves identity: passwords, connection strings with credentials, API keys, OAuth client secrets, signing and encryption keys, SAS tokens and certificate private keys. A database server name or a feature flag isn't a secret; it's configuration. That distinction matters because secrets need rotation, access control and audit, while configuration just needs to be correct.
My first move is to get rid of secrets. In Azure, an App Service, Container App or AKS workload gets a managed identity, and it authenticates to Azure SQL, Blob Storage, Service Bus and Key Vault with Entra tokens. The connection string becomes
Authentication=Active Directory Defaultwith no password, and there's nothing to leak or rotate. For what's left - a Stripe key, a partner's API key, a webhook signing secret - I put it in Key Vault, one vault per environment, and give each app the Key Vault Secrets User role on its own vault only. The app loads secrets through theAddAzureKeyVaultconfiguration provider, so code still usesIOptions<T>and doesn't know where the value came from.Locally, developers either use
dotnet user-secrets, which stores JSON in their user profile outside the repo, or authenticate with their own Entra account throughDefaultAzureCredentialto a dev Key Vault. The mistake I see is treatingappsettings.Development.jsonas 'safe enough' and committing a real key; Git history is forever, so I turn on GitHub push protection or gitleaks in CI. The senior point is that secrets management is mostly about reducing the number of secrets, then controlling and rotating the few you can't remove."
| Value | Secret? | Where it goes |
|---|---|---|
| SQL password / connection string with password | Yes | Remove with managed identity; otherwise Key Vault |
| SQL server and database name | No | appsettings / App Configuration |
| Third-party API key (Stripe, SendGrid) | Yes | Key Vault |
| OAuth client secret | Yes | Prefer certificate or federated credential; else Key Vault |
| JWT signing key / Data Protection key | Yes | Key Vault keys (non-exportable where possible) |
| Storage account key | Yes | Disable shared key; use managed identity + RBAC |
| Feature flag, log level, timeout | No | App Configuration / appsettings |
| Entra tenant id, client id | No | appsettings (they're identifiers, not credentials) |
| Option | How it works | Use when |
|---|---|---|
| Managed identity, no secret | Platform issues tokens to the workload; resource trusts Entra | Target is an Azure service that supports Entra auth |
| Workload identity federation | External workload (GitHub Actions, AKS pod) exchanges its OIDC token for an Entra token | CI/CD and Kubernetes |
| Key Vault + managed identity | Secret stored once; app reads it with its identity | Third-party credentials you can't remove |
| Environment variables from the platform | App Service settings with Key Vault references | Simple apps; still sourced from Key Vault |
| User secrets | JSON in %APPDATA%\Microsoft\UserSecrets or ~/.microsoft/usersecrets |
Local development only |
Moving [a claims API] to managed identity removed [7 of 9] secrets from its configuration: SQL, Storage, Service Bus, Redis (Entra auth) and the Key Vault access itself. The remaining two partner API keys went into Key Vault with a 5-minute reload interval, so rotation no longer needed a redeploy, and the yearly "rotate everything" exercise dropped from [two days of coordinated deploys] to [an hour].
Checks whether the candidate understands secrets as a risk to minimise, not just values to hide, and knows the practical Azure and .NET tooling.
Green flags
Red flags
.gitignore alone is a secrets strategy.A secret is a bearer credential: whoever holds it is the app. Every copy is a place it can leak: the repo, a developer laptop, CI logs, a container image layer, a crash dump, a support ticket. The ACSC's guidance and most Notifiable Data Breaches reports trace a large share of incidents back to compromised credentials. So the strategy is ordered: eliminate, then centralise, then control, then rotate.
App Service / Container App / AKS pod
|
| 1. ask local identity endpoint (IMDS / IDENTITY_ENDPOINT)
v
Azure platform --2. issues Entra access token for audience
| https://database.windows.net/ or https://vault.azure.net
v
App --3. presents token--> Azure SQL / Key Vault / Storage
4. resource validates token, checks RBAC or DB user
There's still a credential, but the platform holds it, rotates it, and it never appears in your configuration. Tokens live about an hour and are cached by Azure.Identity.
DefaultAzureCredential tries, in order: environment variables, workload identity, managed identity, then developer tools (Visual Studio, Azure CLI, Azure PowerShell, azd, and interactive broker options where enabled). That chain is great locally and convenient everywhere, but in production it can pick the wrong credential or add start-up latency while probing. Two common hardening steps:
AZURE_TOKEN_CREDENTIALS=prod (supported in recent Azure.Identity versions) or exclude developer credentials, orManagedIdentityCredential directly in production and DefaultAzureCredential only in Development.Azure.Extensions.AspNetCore.Configuration.Secrets adds Key Vault as a configuration source. Secret names use -- for the : hierarchy separator (Stripe--ApiKey becomes Stripe:ApiKey). Important behaviours:
ReloadInterval re-reads secrets on a timer; combined with IOptionsMonitor<T> the app picks up rotated values without a restart.appsettings.json and environment variables so it wins.KeyVaultSecretManager subclass can filter by prefix when several apps share a vault (better: don't share vaults).Alternative for App Service and Functions: Key Vault references in app settings (@Microsoft.KeyVault(SecretUri=...)), resolved by the platform. No code, but rotation depends on the platform's refresh behaviour (it re-fetches periodically and on restart), and local development needs another source.
dotnet user-secrets init # adds <UserSecretsId> to the csproj
dotnet user-secrets set "Stripe:ApiKey" "sk_test_..."
User secrets are plain JSON in the user profile: kept outside the repo, not encrypted. They're loaded only when the environment is Development (the default builder calls AddUserSecrets for that environment). For shared dev resources, a better option is a dev Key Vault where developers have read access through an Entra group, so nobody copies keys around in chat.
| Leak path | Control |
|---|---|
| Git commits | GitHub secret scanning with push protection, gitleaks pre-commit / CI |
| CI logs | Pipeline secret variables are masked; never echo them; use workload identity federation instead of stored service principal secrets |
| Container images | No ENV or ARG with secrets; BuildKit --secret mounts for build-time needs |
| Application logs | Never log configuration objects; redaction (see the logging question) |
| Crash dumps | Treat dumps as sensitive; restrict and expire them |
SecretNearExpiry events can trigger a rotation Function.dotnet user-secrets init, set a value, and find the JSON file on disk. Note that it's plaintext.Demo--Message, and load it with AddAzureKeyVault and DefaultAzureCredential.IOptionsMonitor<T>.OnChange fire after the reload interval.Authentication=Active Directory Default and create a contained user FROM EXTERNAL PROVIDER for your identity.gitleaks detect on one of your repositories and look at the history, not just the current tree.Program.cs: Key Vault as a configuration source with a managed identity in production and the developer's own sign-in locally:
using Azure.Core;
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
// Production: only the managed identity. Development: the developer's Azure CLI / VS sign-in.
TokenCredential credential = builder.Environment.IsDevelopment()
? new DefaultAzureCredential()
: new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);
if (builder.Configuration["KeyVault:Uri"] is { Length: > 0 } vaultUri)
{
builder.Configuration.AddAzureKeyVault(
new Uri(vaultUri),
credential,
new Azure.Extensions.AspNetCore.Configuration.Secrets.AzureKeyVaultConfigurationOptions
{
// Pick up rotated secrets without a restart.
ReloadInterval = TimeSpan.FromMinutes(5)
});
}
builder.Services.AddOptions<StripeOptions>()
.Bind(builder.Configuration.GetSection(StripeOptions.Section))
.ValidateDataAnnotations()
.ValidateOnStart(); // fail at start-up, not on the first payment
var app = builder.Build();
app.Run();
public sealed class StripeOptions
{
public const string Section = "Stripe";
[System.ComponentModel.DataAnnotations.Required]
public string ApiKey { get; init; } = ""; // Key Vault secret name: Stripe--ApiKey
}
appsettings.json holds identifiers only; the SQL connection uses Entra auth, so there is no password at all:
{
"KeyVault": { "Uri": "https://kv-claims-prod-aue.vault.azure.net/" },
"ConnectionStrings": {
"Claims": "Server=tcp:sql-claims-prod.database.windows.net;Database=Claims;Authentication=Active Directory Default;Encrypt=True"
}
}
Grant the app read access and create its database user:
az role assignment create --assignee <app-principal-id> \
--role "Key Vault Secrets User" \
--scope $(az keyvault show -n kv-claims-prod-aue --query id -o tsv)
CREATE USER [app-claims-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [app-claims-prod];
ALTER ROLE db_datawriter ADD MEMBER [app-claims-prod];
appsettings.Development.json or launchSettings.json because "it's only dev". Why it is wrong: Git history keeps them forever, dev keys often reach shared or production resources, and forks copy them. Instead: Use dotnet user-secrets or a dev Key Vault, and turn on push protection.DefaultAzureCredential in production without thought. Why it is wrong: It can probe several credential types, slowing start-up, and may pick an unintended identity. Instead: Use ManagedIdentityCredential (or restrict the chain) in production.SecretClient. Why it is wrong: It adds latency, hits Key Vault throttling limits, and makes the vault a hard per-request dependency. Instead: Load through configuration at start-up with a reload interval, or cache.Secrets management is mostly an elimination exercise. Count the secrets in a service's configuration, then ask of each one "could an identity replace this?" In Azure the answer is usually yes for everything Microsoft hosts, which leaves a handful of third-party credentials (payment gateways, email providers, partner APIs) that only accept keys. Those get Key Vault, an owner, an expiry and an automated rotation: an Event Grid SecretNearExpiry event triggers a Function that creates a new key at the provider, stores it as a new version, and the app's reload interval picks it up before the old key is revoked. Rotation that needs a coordinated redeploy across five teams won't happen on schedule; that operational friction is the most common reason secrets live for years.
Be honest about the costs. Managed identity and Key Vault put Entra token issuance and the vault on your start-up path: if a private endpoint's DNS is wrong or the vault is throttled (Key Vault has per-vault transaction limits), the app fails to start. Loading through configuration once, caching, and failing fast at start-up keeps that dependency out of the per-request path. A senior engineer also thinks about the non-runtime paths: CI service principals (replace with workload identity federation), Terraform state, container build args, crash dumps.
Measure it: number of long-lived secrets per service, secrets with no expiry date, mean time to rotate, and push-protection blocks per month.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Managed identity | Target is an Azure service with Entra auth | RBAC setup, DB users, token endpoint dependency | Third-party APIs that only take keys |
| Key Vault config provider | App needs secrets via IOptions with reload |
Start-up dependency, throttling limits | Per-request dynamic secret retrieval |
| App Service Key Vault references | Simple App Service / Functions apps | Platform-controlled refresh timing | Local dev, containers outside App Service |
| User secrets | Local development | Plaintext on the laptop | Anything shared or production |
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
Properties/launchSettings.json defines launch profiles for local development: how to start the app, which URLs, and which environment variables. Visual Studio, Rider, VS Code with C# Dev Kit and dotnet run all read it, but it is not published. In this file I would flag: secrets are committed (a production connection string and API key), so they must be rotated now and moved to user secrets; the environment is Production, which switches on production behaviour and turns off user secrets, and combined with the production connection string means a developer's F5 talks to the live database; and it binds to 0.0.0.0 over plain HTTP, exposing the app to the network. I would replace it with HTTPS and HTTP profiles on localhost using Development, and add a separate production-like profile only if someone needs to test production behaviour against non-production resources.
Register the API in Entra ID with an App ID URI, delegated scopes (Orders.Read) for user calls and app roles (Orders.Read.All) for application calls. Register each client separately and grant it those permissions. In the API, AddMicrosoftIdentityWebApi (Microsoft.Identity.Web) wires up JWT bearer validation against your tenant.
scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.api://<app-id>/.default; you assign it an app role.The trade-off: Entra does the heavy lifting, but permissions and consent live in the portal, so manage them as code.
Last updated 23 Nov 2026.