Azure Key Vault & Secrets
Azure Key Vault protects secrets, cryptographic keys, and certificates behind Microsoft Entra authentication, data-plane authorization, recovery controls, and audit logs.
Overview
Key Vault removes sensitive material from source repositories and ordinary application settings, but it does not remove the need to design identity, authorization, retrieval, caching, rotation, recovery, and leakage controls. .NET workloads commonly authenticate with DefaultAzureCredential during development and a managed identity in Azure, then use SecretClient for explicit version-aware retrieval or the ASP.NET Core configuration provider for startup-oriented configuration. Production vaults should use Azure RBAC, least-privilege data roles, separate environment boundaries, soft delete, purge protection, diagnostics, network restrictions where required, and tested rotation with overlapping validity. Applications must decide whether they follow the latest secret version or pin a version, how quickly caches refresh, what happens during vault failure, and how dependent services adopt a new credential without downtime. A retrieved secret becomes ordinary process memory and can still leak through logs, exceptions, telemetry, dumps, responses, or an over-privileged caller.
What you will learn
- Distinguish secrets, keys, certificates, control-plane operations, and data-plane operations.
- Authenticate .NET workloads with DefaultAzureCredential and managed identity without a deployed client secret.
- Choose Azure RBAC roles, scope, vault boundaries, and network controls using least privilege.
- Select explicit SecretClient retrieval or configuration-provider integration by refresh and version needs.
- Design cache, version, rotation, overlap, rollback, and outage behavior.
- Protect deletion recovery and observe access without logging values.
- Test identity, denial, rotation, recovery, and deployed network paths.
Prerequisites
- ASP.NET Core configuration, dependency injection, options, and application startup.
- Microsoft Entra identities, OAuth tokens, Azure RBAC scope, and managed identity basics.
- Secret rotation and zero-downtime deployment concepts.
- A .NET 10 SDK to run the dedicated rotation sample.
When to use Azure Key Vault & Secrets
Good fit
- Use Key Vault for centrally governed application secrets, keys, and certificates that require auditable access and lifecycle controls.
- Use managed identity for Azure workloads and approved developer credentials locally.
- Use SecretClient when code needs explicit versions, metadata, refresh, writes, or rotation coordination.
- Use the configuration provider for secrets that naturally map to startup configuration and whose refresh behavior is acceptable.
Choose another approach when
- Do not store ordinary non-sensitive configuration in Key Vault by default.
- Do not embed a client secret just to retrieve another secret.
- Do not grant broad administrator roles to runtime identities.
- Do not assume secret rotation automatically refreshes every application instance.
Key concepts
Secrets hold sensitive values, keys support cryptographic operations, and certificates manage certificate material and lifecycle.
An Azure-hosted workload obtains short-lived Entra tokens without storing a client secret in source code or application configuration.
Separate control-plane and data-plane roles grant narrowly scoped management or object access and can be audited centrally.
Updating a secret creates a version; consumers need an intentional latest-versus-pinned policy and controlled adoption.
Bounded application caches reduce latency and vault load while defining how long an old value can remain active.
Zero-downtime rotation usually creates a new credential, overlaps validity, updates dependents, verifies adoption, then revokes the old value.
Soft delete and purge protection defend vaults and objects against accidental or malicious deletion and require rehearsed recovery.
Firewall or private connectivity constrains reachability while diagnostic logs provide access and change evidence without exposing values.
Architecture
The .NET workload uses its Entra identity to request narrowly authorized Key Vault data, while diagnostics and rotation processes govern access throughout the secret lifecycle.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
The application adds Key Vault as a configuration source and uses the same credential chain for local development and managed identity in Azure.
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
var vaultUri = builder.Configuration["KeyVault:Uri"];
if (!string.IsNullOrWhiteSpace(vaultUri))
{
builder.Configuration.AddAzureKeyVault(
new Uri(vaultUri),
new DefaultAzureCredential());
}
builder.Services.Configure<PaymentOptions>(
builder.Configuration.GetSection("Payments"));
var app = builder.Build();
app.Run();
public sealed record PaymentOptions
{
public required string ApiKey { get; init; }
}Testing strategy
Separate application tests from real identity, vault, network, rotation, and recovery verification.
- Unit-test application behavior with a secret-provider abstraction; never require a real vault for every logic test.
- Integration-test DefaultAzureCredential with a dedicated non-production identity and least-privilege role.
- Verify unauthorized identities cannot list or read secrets and runtime identities cannot administer the vault.
- Run a two-version rotation drill proving old and new values overlap, adoption is observable, rollback works, and old credentials are revoked.
- Test missing, disabled, expired, deleted, malformed, throttled, and unreachable secret states with redacted errors.
- Recover a deleted object or disposable vault in a rehearsal and record recovery time and permissions.
Security considerations
Protect identity, authorization, network reach, recovery controls, administrators, and every place resolved material can escape.
- Use managed identity in Azure and approved developer identity or local secret storage; never commit credentials.
- Prefer Azure RBAC and separate runtime read roles from secret-management and vault-administration roles.
- Use separate vaults or strong boundaries per environment and avoid cross-environment runtime access.
- Enable purge protection and diagnostics; restrict public access and use private endpoints when threat and compliance needs justify them.
- Never log values, authorization headers, configuration dumps, exception payloads, process dumps, or fingerprints that enable guessing.
- Treat the process, operators, deployment system, backups, and downstream service as part of the secret exposure boundary.
Performance and scalability
Reuse clients and credentials, cache deliberately, and observe retrieval pressure without weakening rotation objectives.
- Reuse Azure SDK clients and token credentials; they are designed for concurrent use.
- Cache values for a bounded period chosen from rotation objectives and compromise response requirements.
- Avoid listing or retrieving secrets per request; fetch only named objects and prevent cache stampedes.
- Use bounded retries with jitter for transient throttling and respect service guidance rather than retrying authorization failures.
- Measure retrieval latency, failures, throttles, cache age, refresh outcomes, version adoption, and dependency authentication errors.
- Estimate startup fan-out across replicas and stagger refresh so a deployment does not overload the vault.
Deployment and operations
Deploy identity, access, recovery, and networking before consumers, then rotate through observable overlapping versions.
- Provision vault policy, RBAC assignments, diagnostics, recovery, and networking through reviewed infrastructure as code.
- Create identities and role assignments before workloads need the secret and allow for RBAC propagation.
- Use environment-specific URIs and secret names while keeping values out of templates, outputs, pipeline logs, and source control.
- Deploy network and DNS paths before disabling public access; test from the actual hosting environment.
- Rotate with overlapping validity, staged consumer refresh, version telemetry, rollback, and final old-credential revocation.
- Maintain emergency access, break-glass audit, ownership, expiration alerts, and recovery runbooks.
Common problems and fixes
DefaultAzureCredential works locally but fails in Azure
Likely cause: The deployed identity is missing, the wrong identity is selected, or its data role and scope are incorrect.
Fix: Inspect the host identity, credential diagnostics, tenant, client ID when user-assigned, role definition, scope, and propagation time.
The caller gets forbidden despite a role
Likely cause: A control-plane role was confused with a data-plane role, scope is wrong, or the vault uses a different permission model.
Fix: Confirm enableRbacAuthorization, assign the narrow data role, remove conflicting assumptions, and retest after propagation.
A rotated value is not used
Likely cause: The app pins a version, caches longer than expected, or the configuration provider does not refresh automatically as assumed.
Fix: Inspect requested version and cache age, invalidate deliberately, restart only when documented, and graph adoption before revoking old credentials.
Private endpoint access fails
Likely cause: DNS resolves the public endpoint, routing or firewall rules block traffic, or deployment agents have no private path.
Fix: Resolve the vault hostname from the workload, inspect private DNS links, routes, endpoint approval, firewall, and deployment topology.
Vault throttling causes request failures
Likely cause: Clients are recreated, values are fetched per request, replicas refresh together, or retries amplify load.
Fix: Reuse clients, add bounded caches and single-flight refresh, stagger work, honor backoff, and inspect service metrics.
A deleted secret cannot be restored
Likely cause: The recovery window expired, permissions are insufficient, purge occurred, or the runbook was never tested.
Fix: Verify soft-delete state and retention, use authorized recovery procedures, restore dependent configuration, and rehearse before an incident.
Best practices
- Use managed identity for Azure workloads and developer identity or approved local secret storage during development.
- Prefer Azure RBAC data-plane roles, least privilege, separate environment boundaries, and just-in-time administration.
- Use explicit version and cache policies rather than assuming every consumer follows rotation automatically.
- Design rotation with overlapping validity, adoption telemetry, rollback, and dependency coordination.
- Enable diagnostics, purge protection, recovery alerts, and tested restore procedures.
- Restrict network access where required and validate DNS and routing from the deployed workload.
- Avoid logging resolved values and review every place a retrieved secret can escape process memory.
Production checklist
- Secret inventory, ownership, consumers, expiration, rotation, recovery, and deletion policy are recorded.
- Managed identity and least-privilege Azure RBAC data roles are verified at the intended scope.
- Environment separation, network path, private DNS or firewall, and emergency access are tested.
- Soft delete, purge protection, diagnostics, alerts, and audit retention are enabled.
- Retrieval choice, version policy, cache lifetime, retries, startup behavior, and outage fallback are documented.
- Secret values are excluded from logs, errors, telemetry, responses, dumps, templates, and pipeline outputs.
- Two-version rotation, staged adoption, rollback, and old-credential revocation are rehearsed.
- Deletion recovery and deployed-environment access are verified regularly.
Common interview questions
Why use managed identity with Key Vault?
It removes the need to distribute and rotate an application credential for accessing the vault; Azure issues short-lived tokens to the workload identity.
What is the difference between the Key Vault control plane and data plane?
The control plane manages the vault resource and settings, while the data plane operates on secrets, keys, and certificates. Permissions should be scoped separately.
When should .NET use SecretClient instead of the configuration provider?
Use SecretClient when code needs explicit versions, metadata, refresh timing, writes, or fine-grained error handling. The provider fits startup-oriented configuration mapping when its loading and refresh behavior are acceptable.
How do you rotate a credential without downtime?
Create a new credential, allow old and new values to overlap, publish and activate the new version, observe all consumers adopting it, retain rollback, then revoke the old credential.
Why cache Key Vault secrets?
Caching reduces latency, cost, throttling, and outage impact, but the lifetime must be bounded so rotation and compromise response meet objectives.
Does rotating a Key Vault secret automatically update every running application?
No. A new version becomes available, but each integration has its own caching and refresh behavior. Applications need a tested strategy for observing and adopting the new value.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Key Vault Rotation API
A .NET 10 versioned-secret lifecycle model with deliberate activation, bounded caching, redacted metadata, and recovery-protected Azure RBAC Bicep.
- Run
dotnet run --project src/KeyVaultRotationApi- Test
dotnet test KeyVaultRotationApi.slnx