Module 1 · Cloud-Native Foundations · Lesson 2 of 12
Configuration and Secrets for Cloud-Native .NET: Layering, Mounted Secrets, Key Vault and Validation
Cloud-native .NET configuration combines safe defaults with deployment settings and protected secrets. Validate settings at startup, and make secret rotation reach the running code.
It turns twelve-factor configuration and disposability into concrete choices: which source wins, how Kubernetes supplies values, and what must happen after a secret changes.
What should go in appsettings.json?
Keep safe, shared defaults in appsettings.json. Supply credentials, real service addresses and the environment name when you deploy the app. The same image can then run in different environments without rebuilding it.
For example, these retry settings are safe to ship:
{
"Delivery": {
"MaxAttempts": 3
}
}The production delivery address and API key are deliberately absent. Deployment configuration must provide them, and startup validation should reject them if they are missing.
Set ASPNETCORE_ENVIRONMENT externally before the ASP.NET Core app starts. It helps select environment-specific behavior and configuration, including appsettings.{Environment}.json. Do not bake a populated production settings file into the image. A file named appsettings.Production.json is not a secret store.
For local development, use Secret Manager (user secrets) with invented credentials or development-only secrets. It stores secrets in your user profile, outside the project. They are not encrypted. With the default ASP.NET Core configuration, user secrets are loaded only in Development. Never use production secrets locally or in tests.
The mistake to avoid. Removing credentials from source control is not enough if a build step copies them into the image. Anyone able to retrieve that image may also retrieve its files.
In an interview, say: “I keep safe defaults in appsettings.json. I supply secrets, service addresses and ASPNETCORE_ENVIRONMENT at deployment time, rather than building environment-specific credentials into the image.”
Which configuration source wins in ASP.NET Core?
A configuration provider reads settings from a particular source, such as JSON, environment variables or files. Several providers can supply the same key.
The last registered provider containing that key wins. This rule applies separately to each key. A later provider does not erase unrelated settings from earlier providers.
With the default sources, environment variables override the JSON files, and the command line overrides both. That is only registration order: a provider you append later, such as AddKeyPerFile or Key Vault, wins over all of them for its keys. The program later in this lesson shows this. Configuration providers, reload and options validation covers the full default order.
Azure Key Vault is Azure's managed service for storing secrets; an app can load them into configuration.
The mistake to avoid. Do not say “command line always wins.” Adding Key Vault or mounted files after the default sources can change the winning value.
In an interview, say: “The last registered provider containing the key wins. Environment variables normally override JSON, and command line normally follows them. A provider I append afterward can override command-line values too.”
How do Kubernetes ConfigMaps and Secrets reach a .NET app?
Kubernetes manages containerized applications across a group of machines called a cluster. A pod is its smallest deployable unit and contains one or more containers that run together.
A ConfigMap holds ordinary configuration, such as a service address or retry limit. A Secret holds sensitive data, such as an API key.
You can expose their values to a container in two common ways:
| Delivery method | What the app receives | .NET configuration support |
|---|---|---|
| Environment variables | Values available when the process starts | Included in the usual ASP.NET Core defaults |
| Mounted files | Files placed at a directory inside the container | Add a suitable file provider, such as AddKeyPerFile |
A mounted volume makes externally supplied files visible inside a container.
For environment variables, Delivery__ApiKey maps to the configuration key Delivery:ApiKey. The double underscore represents a section separator and works across platforms.
AddKeyPerFile uses each file's name as a configuration key and its contents as the value. It also converts double underscores to section separators. A file named Delivery__ApiKey therefore supplies Delivery:ApiKey.
Use an absolute directory path when calling AddKeyPerFile.
This pod-spec fragment assumes a Secret named delivery-secrets already contains a key named Delivery__ApiKey. It shows both delivery methods for comparison:
spec:
containers:
- name: app
image: example.invalid/delivery:demo
env:
- name: Delivery__ApiKey
valueFrom:
secretKeyRef:
name: delivery-secrets
key: Delivery__ApiKey
volumeMounts:
- name: app-secrets
mountPath: /run/secrets/app
readOnly: true
volumes:
- name: app-secrets
secret:
secretName: delivery-secretsThe volume supplies /run/secrets/app/Delivery__ApiKey. Point AddKeyPerFile at /run/secrets/app to read it.
The experiment below creates an invented secret file and reads it this way. For the Kubernetes objects that supply real mounts, see Kubernetes Basics for .NET Developers.
The mistake to avoid. Do not assume a mounted directory is already part of IConfiguration. Kubernetes supplies files; your app must register a provider that reads their format.
In an interview, say: “I inject ConfigMaps for ordinary settings and Secrets for sensitive settings, using environment variables or mounted files. Section__Key maps to Section:Key. For one-value-per-file mounts, I register AddKeyPerFile and check where it sits in provider order.”
Is a Kubernetes Secret encrypted?
A Kubernetes Secret's data field uses base64 encoding. Encoding is not encryption: anyone can decode it without a key, for example with Convert.FromBase64String.
Protect Kubernetes Secrets with RBAC, or role-based access control: permissions that limit which identities can perform particular operations. Grant only the access each application or operator needs.
Also protect stored Secret data with encryption at rest (the data is encrypted on the disk where the cluster stores it). Kubernetes stores its state in etcd, its backing data store. Check your cluster's encryption configuration rather than assuming Secret means encrypted.
Key Vault can hold the source secret, but copies still need protection. A mounted file or a synchronized Kubernetes Secret remains sensitive.
Never log secret values. Do not dump all configuration during troubleshooting. Log a validation result, refresh result or approved non-sensitive deployment identifier instead. Secret prefixes and lengths are not appropriate diagnostic evidence either.
The mistake to avoid. Do not treat base64 text as safe to commit, print or attach to a support ticket. Anyone who can read it can decode it.
In an interview, say: “A Kubernetes Secret is not secure just because its data is base64-encoded. I restrict access with RBAC, protect etcd data with encryption at rest, and keep secret values out of logs. Key Vault does not remove the need to protect mounted or copied values.”
When does a running app see a rotated secret?
Rotation means replacing a credential with a new one. Changing the source secret is only the first step.
For environment-variable injection, restart the pod to receive the new value. Updating the Kubernetes Secret does not rewrite the environment of an already running process.
Mounted Secret volumes can receive updates eventually, rather than immediately. A subPath mount places just one file from a Secret or ConfigMap at a chosen path. Kubernetes does not update files mounted this way when the Secret or ConfigMap changes. Avoid that mount style when you depend on automatic updates.
For a file-based route, the full path looks like this:
flowchart TD
S["External secret store"] -->|"supplies updates"| F["Mounted file"]
F -->|"provider reloads"| C[".NET configuration"]
C -->|"consumer refreshes"| U["Code using the credential"]
First, confirm that the external delivery mechanism updated the mounted file. Next, confirm that the configuration provider reloaded it. Finally, confirm that the code using the credential adopted the new value.
For AddKeyPerFile, reloadOnChange: true enables file-change reload. Kubernetes replaces mounted Secret files by switching a symbolic link, so file-change events may not fire: test with your real volume, and consider polling (checking files periodically) or an explicit reload. The experiment calls Reload() so its result does not depend on watcher timing.
IOptionsMonitor<T> provides current options and change notifications when the underlying configuration supports reload. Reading CurrentValue again can obtain refreshed options. Keeping an old options object or a client constructed with an old credential does not update that object or client automatically.
Test rotation using non-sensitive status evidence: an observed file-update result, a provider-refresh result and a successful authenticated operation with the replacement credential. In a test, switch off the old credential once the overlap time has passed. If some code still uses the old one, it will now fail, so you can find it.
The mistake to avoid. A successful update in the secret store does not prove the app is using the replacement. Check external delivery, provider reload and consumer refresh separately.
In an interview, say: “Environment variables require a pod restart. Mounted files update eventually, except subPath mounts. The provider must reload and consumers must adopt the new value. Key Vault polling or CSI autorotation also has to be configured when that is the delivery route.”
Should I use the Key Vault provider or CSI-mounted files?
There are two common ways to bring Key Vault secrets into .NET configuration.
The in-app provider loads them through application code. Register it with AddAzureKeyVault from the Azure.Extensions.AspNetCore.Configuration.Secrets package. The credential below comes from Azure.Identity.
This example needs those packages, a real vault address and a workload identity allowed to read the vault, so it is not run here:
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
var vaultUri = "https://example-vault.vault.azure.net/";
builder.Configuration.AddAzureKeyVault(
new Uri(vaultUri), new WorkloadIdentityCredential(),
new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });
var app = builder.Build();
app.Run();The registration loads secrets using workload identity and requests a refresh every five minutes. Key Vault secret names use -- for hierarchy: Delivery--ApiKey becomes Delivery:ApiKey.
Periodic reload is off unless you set ReloadInterval; polling adds Key Vault requests and a delay before updates appear. The provider's position in registration order still decides which settings it overrides.
The Secrets Store CSI Driver mounts external secrets as files. CSI means Container Storage Interface, the interface Kubernetes uses to integrate storage systems. The Azure Key Vault provider for this driver brings vault contents into a pod volume without an in-app Key Vault dependency.
Your app can read that directory with AddKeyPerFile. The operational cost moves to cluster setup: the driver, identity permissions and mount configuration must be managed.
Enable CSI autorotation, the driver's periodic refresh of mounted values, when updates must reach running pods. In Azure Kubernetes Service (AKS), its default polling interval is two minutes once autorotation is enabled. Synchronizing to a Kubernetes Secret and injecting it as an environment variable still requires a pod restart.
Both routes need an Azure identity with read access to the vault. On AKS, use workload identity: no client secret is stored, and in-app code uses an explicit WorkloadIdentityCredential rather than the DefaultAzureCredential chain. AKS for .NET Teams shows the setup.
The mistake to avoid. Do not replace an application password with a long-lived client secret used only to fetch that password. Where supported, use workload identity and grant only the required vault access.
In an interview, say: “The Key Vault configuration provider loads secrets through in-app code. CSI mounts them as files without an in-app Key Vault dependency, but needs cluster setup. Both can use workload identity. I configure provider polling or CSI autorotation, and still refresh the consumers.”
How do I validate configuration at startup and test a secret reload?
Register options validation and call ValidateOnStart. Invalid values then fail host startup instead of waiting until the options are first accessed.
The experiment below needs the hosting and key-per-file packages; every credential is invented.
Before reading the explanation, predict which startup succeeds and whether the previously captured options object changes.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
string directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
string secretFile = Path.Combine(directory, "Delivery__ApiKey");
try
{
await CheckAsync(0);
await CheckAsync(3);
}
finally
{
Directory.Delete(directory, recursive: true);
}
async Task CheckAsync(int maxAttempts)
{
File.WriteAllText(secretFile, "invented-first");
var builder = Host.CreateApplicationBuilder(new[]
{
"--Delivery:MaxAttempts=9"
});
builder.Logging.ClearProviders();
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["Delivery:Endpoint"] = "https://delivery.example.invalid",
["Delivery:MaxAttempts"] = maxAttempts.ToString()
});
builder.Configuration.AddKeyPerFile(
directory, optional: false, reloadOnChange: false);
builder.Services.AddOptions<DeliveryOptions>()
.Bind(builder.Configuration.GetSection("Delivery"))
.Validate(o => o.MaxAttempts is >= 1 and <= 5,
"Delivery attempt count is invalid.")
.Validate(o => Uri.TryCreate(o.Endpoint, UriKind.Absolute, out var uri)
&& uri.Scheme == Uri.UriSchemeHttps,
"Delivery endpoint must be an absolute HTTPS address.")
.Validate(o => !string.IsNullOrWhiteSpace(o.ApiKey),
"Delivery credential is required.")
.ValidateOnStart();
using var host = builder.Build();
try
{
await host.StartAsync();
}
catch (OptionsValidationException)
{
Console.WriteLine("Startup rejected invalid configuration.");
return;
}
var monitor = host.Services.GetRequiredService<IOptionsMonitor<DeliveryOptions>>();
// Record whether the options monitor reports a change.
bool changeNotified = false;
using var subscription = monitor.OnChange(_ => changeNotified = true);
var captured = monitor.CurrentValue;
Console.WriteLine($"Startup accepted; attempts={captured.MaxAttempts}");
File.WriteAllText(secretFile, "invented-replacement");
Console.WriteLine($"External file updated: {File.ReadAllText(secretFile) == "invented-replacement"}");
((IConfigurationRoot)builder.Configuration).Reload();
Console.WriteLine($"Provider refreshed: {builder.Configuration["Delivery:ApiKey"] == "invented-replacement"}");
Console.WriteLine($"Consumer refreshed: {monitor.CurrentValue.ApiKey == "invented-replacement"}");
Console.WriteLine($"Change notification received: {changeNotified}");
Console.WriteLine($"Captured object refreshed: {captured.ApiKey == "invented-replacement"}");
await host.StopAsync();
}
public sealed class DeliveryOptions
{
public string Endpoint { get; set; } = "";
public string ApiKey { get; set; } = "";
public int MaxAttempts { get; set; }
}Startup rejected invalid configuration. Startup accepted; attempts=3 External file updated: True Provider refreshed: True Consumer refreshed: True Change notification received: True Captured object refreshed: False
The first call supplies zero attempts, outside the allowed range of one to five. The catch block reports a validation failure without printing configuration values.
The second call supplies three attempts and succeeds. The command line supplied nine, but the in-memory provider was appended afterward and supplied three.
The temporary file supplies Delivery:ApiKey. After the file changes and the configuration reloads, the provider and IOptionsMonitor.CurrentValue see the new key, but the object captured before the reload still holds the old one.
Startup validation stops a bad pod from becoming ready; old pods keep serving only if readiness probes and rollout settings allow it.
The mistake to avoid. Registering validators is not the same as validating during startup. Use ValidateOnStart, and do not assume it also controls Kubernetes traffic or replacement policy.
In an interview, say: “I bind options, register validation rules and call ValidateOnStart. Invalid configuration then fails host startup instead of failing on first access. Keeping old pods serving also depends on readiness checks and rollout settings.”
Check yourself
A Secret supplies Delivery__ApiKey as an environment variable. You replace the Secret value. What must happen for the app to receive it through that environment variable?
Show answer
Correct answer: B
Updating a Secret does not rewrite an existing process environment. Options refresh cannot obtain a value that has not reached the process.
An app uses the default configuration sources, then appends AddKeyPerFile. The command line and a mounted file both supply Delivery:MaxAttempts. Which value wins?
Show answer
Correct answer: D
The last registered provider containing a key supplies its value. Appending a provider can override command-line settings.
Going deeper
Reload failures need a policy. Startup validation checks startup configuration, not the future availability or correctness of every replacement secret. Decide how the app handles an invalid update, failed refresh or credential rejected by the downstream service. Do not assume options validation automatically retains a last-known-good value.
Vault metadata needs attention. The Key Vault configuration provider includes expired secrets by default and skips disabled ones. An expiry timestamp alone does not make it reject a secret; apply the documented filtering if you need that.
Separate identities and access scope. Avoid one broadly authorized identity shared across unrelated applications.
Sources
- Configuration in ASP.NET Core | Microsoft Learn: Default configuration ordering, last-provider precedence, environment-variable hierarchy, key-per-file configuration, environment-specific files and secret storage guidance.
- Options pattern - .NET | Microsoft Learn: Options binding, deferred validation, ValidateOnStart, IOptionsMonitor and refreshed options.
- Azure Key Vault configuration provider | Microsoft Learn: AddAzureKeyVault, double-hyphen key mapping, ReloadInterval, authorization requirements and handling of expired and disabled secrets.
- Use the Azure Key Vault provider for Secrets Store CSI Driver in an Azure Kubernetes Service (AKS) cluster: CSI-mounted secrets, Kubernetes Secret synchronization, identity authorization and subPath update limitations.
- Azure Key Vault provider for Secrets Store CSI Driver for Azure Kubernetes Service (AKS) configuration options: Enabling autorotation, default two-minute poll interval, mounted-file watching and pod restarts for environment-variable consumers.
- Credential chains in the Azure Identity library for .NET: DefaultAzureCredential chain behavior and choosing an explicit production credential.
- Microsoft Entra Workload ID overview: Kubernetes service accounts, federated token exchange and Azure access without a stored client secret.
- Security concepts for applications and clusters in Azure Kubernetes Service (AKS): Kubernetes RBAC, protecting Secrets and encryption of stored cluster data.
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 30 Nov 2026 ·