In ASP.NET Core 10, how do you load production secrets from Azure Key Vault with AddAzureKeyVault and DefaultAzureCredential, and what happens at startup when access fails?
answer
- Azure.Extensions.AspNetCore.Configuration.Secrets
- AddAzureKeyVault(vaultUri, credential)
- list then get, during startup
- first credential in the chain wins
- CredentialUnavailableException or RequestFailedException 403
basics
~10 sReference Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity, then call builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential()). The provider lists and reads every enabled secret while the source is added, so a missing credential or permission stops startup with an exception.
solid answer
~40 sWith ASP.NET Core 10 you add `Azure.Extensions.AspNetCore.Configuration.Secrets` (1.5.2) and `Azure.Identity`, then call `builder.Configuration.AddAzureKeyVault(new Uri("https://<vault>.vault.azure.net/"), new DefaultAzureCredential())`, usually only in Production. `ConfigurationManager` loads the source immediately: the provider lists the vault's secrets, skips disabled ones, fetches the values and maps `Maps--ApiKey` to `Maps:ApiKey`. `DefaultAzureCredential` tries credentials in order (environment variables, workload identity, managed identity, then developer tools such as Visual Studio and the Azure CLI) and keeps the first one that returns a token. If none can, startup fails with `CredentialUnavailableException`; if the identity lacks permission to list or read secrets, the vault answers 403 and `RequestFailedException` stops the app. At startup nothing degrades silently, and the values are loaded once unless a reload interval is set.
code
csharp · 16 linesusing Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
if (!builder.Environment.IsDevelopment())
{
var vaultUri = new Uri(builder.Configuration["KeyVault:VaultUri"]
?? throw new InvalidOperationException("KeyVault:VaultUri is not set."));
// throws here if no credential works or access is denied
builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential());
}
// secret Maps--ApiKey in the vault, Maps:ApiKey in Secret Manager locally
string mapsKey = builder.Configuration["Maps:ApiKey"]
?? throw new InvalidOperationException("Maps:ApiKey is not set.");go deeper
Know that production secrets can come from Azure Key Vault through AddAzureKeyVault and are then read like any other configuration key.
Explain the two packages, the -- to : naming, and that DefaultAzureCredential uses a developer sign-in locally and the host identity in Azure.
Expect eager, synchronous loading of every secret, pin the credential chain in production, and treat 403 or credential failures at startup as deployment errors.
Decide vault boundaries per app and environment and which identity may read each, weighing startup cost and blast radius against operational overhead.
## Packages and the call The Key Vault configuration provider is not part of ASP.NET Core; it ships as **`Azure.Extensions.AspNetCore.Configuration.Secrets`** (1.5.2 at the time of writing), alongside **`Azure.Identity`** for the credential. In Azure.Identity 1.21.0 the credential types are forwarded to Azure.Core 1.63.0, but code still uses the `Azure.Identity` namespace, so nothing changes in `Program.cs`. ASP.NET Core 10 itself does not reference the provider. ```csharp using Azure.Identity; var builder = WebApplication.CreateBuilder(args); if (builder.Environment.IsProduction()) { var vaultUri = new Uri(builder.Configuration["KeyVault:VaultUri"] ?? throw new InvalidOperationException("KeyVault:VaultUri is not set.")); builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential()); } ``` `AddAzureKeyVault` lives in the `Microsoft.Extensions.Configuration` namespace, so no extra `using` is needed for it. Overloads also accept a `SecretClient`, a custom `KeyVaultSecretManager`, or an `AzureKeyVaultConfigurationOptions` object. ## What happens when the source is added `builder.Configuration` is a `ConfigurationManager`, which builds and loads a source the moment it is added. The provider's `Load` then: 1. lists the properties of every secret in the vault; 2. skips secrets that are disabled or that the secret manager's `Load(SecretProperties)` rejects (the default accepts all, including expired ones); 3. fetches the values, up to 32 requests in parallel; 4. turns each name into a key, replacing `--` with `:`, so the secret `Maps--ApiKey` becomes `Maps:ApiKey`. All of this is synchronous network I/O during startup, so a vault with many secrets adds visible start time, and every enabled secret in the vault is read whether the app needs it or not. That is one reason to give each app and environment its own vault. ## How DefaultAzureCredential picks an identity `DefaultAzureCredential` walks a chain and keeps the first credential that returns a token: | Order | Credential | Typical source | |---|---|---| | 1 | `EnvironmentCredential` | `AZURE_CLIENT_ID` and related variables | | 2 | `WorkloadIdentityCredential` | Federated token file in a cluster | | 3 | `ManagedIdentityCredential` | The host's managed identity | | 4-8 | `VisualStudioCredential`, `VisualStudioCodeCredential`, `AzureCliCredential`, `AzurePowerShellCredential`, `AzureDeveloperCliCredential` | A developer's sign-in | | excluded | `InteractiveBrowserCredential` | Off unless explicitly enabled | The same code therefore uses a developer's sign-in on a laptop and the host's identity in Azure. The convenience has a cost: the chain may pick something unexpected, such as stray `AZURE_*` variables winning over the managed identity. Setting `AZURE_TOKEN_CREDENTIALS` to `prod` or `dev` narrows the chain to the deployed or the developer credentials, and the provider docs suggest a specific credential such as `ManagedIdentityCredential` in production. ## Failure modes at startup | Situation | What stops the app | |---|---| | No credential in the chain can produce a token | `CredentialUnavailableException`, a subclass of `AuthenticationFailedException` | | A credential fails with an unexpected error | `AuthenticationFailedException` | | The identity may not list or read secrets | `RequestFailedException` with `Status` 403 | | The vault URI is wrong or unreachable | `RequestFailedException` after the client's retries | The exception escapes `AddAzureKeyVault`, so `Program.cs` never reaches `builder.Build()`. That is usually what you want: an app that cannot read its maps key should not take traffic. ## Placement and local development - Added after `CreateBuilder`, the vault source is the **last** source, so its values beat environment variables and command-line arguments. - Gate the call on the environment or on a configured URI, and keep the same key names in Secret Manager locally, so code reads `Maps:ApiKey` whatever supplies it. - Values are loaded **once**; a rotated secret reaches the app only after a restart or with a reload interval. ## Interview checklist - Two packages, one call, `--` mapped to `:`. - Loading is eager, synchronous and all-secrets. - Recite the credential chain and say the first success sticks. - Name the startup exceptions and why failing fast is right.
- On a server, DefaultAzureCredential authenticates as a service principal instead of the host's managed identity. Why?The chain is ordered and the first credential that returns a token wins. `EnvironmentCredential` comes before `ManagedIdentityCredential`, so leftover `AZURE_CLIENT_ID`, `AZURE_TENANT_ID` and secret variables on that machine win, and the chosen credential is then reused. Remove the variables, set `AZURE_TOKEN_CREDENTIALS=prod`, or construct the specific credential you intend.
- Which permissions does the app's identity need on the vault for AddAzureKeyVault?Permission to list secrets and to read their values. The provider first enumerates the vault, then fetches each enabled secret; without list it cannot enumerate, and without get it cannot read. Either gap surfaces as `RequestFailedException` with status 403 during startup.
- Why might a large shared vault slow down startup or leak secrets into an app?The default provider loads every enabled secret in the vault, synchronously, before the app is built. A vault shared by several apps means each app pays for and holds every other app's secrets in its configuration. Separate vaults per app and environment, or a manager whose `Load` filters secrets, keep both cost and exposure down.
- AddAzureKeyVault fetches a secret lazily the first time its key is read.
- DefaultAzureCredential always uses the managed identity, even on a developer laptop.
- Key Vault secret names can contain a colon, like Maps:ApiKey, to form sections.
- If the vault is unreachable, the provider logs a warning and the app starts with file values.
- Disabled secrets are loaded with an empty value so the key still exists.
Assumes ASP.NET Core 10 with Azure.Extensions.AspNetCore.Configuration.Secrets 1.5.2 and Azure.Identity 1.21.0, whose credential types are now forwarded to Azure.Core 1.63.0 under the unchanged Azure.Identity namespace.