Delivery & OperationsComplete guide

Secrets Management

Secrets management is about where credentials live, who and what can read them, and how they get replaced—not just picking a vault product to store them in.

Overview

A secret checked into source control or placed in a distributable configuration file must be treated as compromised because Git history, forks, artifacts, backups, logs, telemetry, and developer machines outlive later deletion. The strongest strategy first removes secrets by using workload identity, managed identity, federation, certificates, or platform integration. Remaining passwords, keys, connection strings, and tokens belong in a dedicated store with identity-based access, least-privilege data-plane roles, environment isolation, audit logs, recovery protection, expiration, versioning, and rotation. Applications must retrieve only what they need, avoid copying values into logs or broad process state, cache for a bounded time, refresh without restart, support overlapping credential versions, fail closed when required material is unavailable, and expose metadata rather than values for diagnostics. Operations must cover creation, distribution, use, rotation, revocation, recovery, deletion, incident response, and ownership. A vault is not magic: an overprivileged workload, exported environment dump, unsafe exception, compromised build agent, or unredacted telemetry can still leak every value it can read.

What you will learn

  • Classify secrets separately from ordinary configuration and public identifiers.
  • Eliminate credentials with workload identity or federation before deciding how to store them.
  • Design least-privilege vault, identity, network, audit, recovery, and environment boundaries.
  • Retrieve, cache, refresh, and redact secrets safely in .NET applications.
  • Design rotation with versions, overlap, rollout, verification, rollback, and revocation.
  • Respond correctly to repository, pipeline, log, host, or runtime secret exposure.
  • Test secret lifecycle behavior without embedding live credentials in the test suite.

Prerequisites

  • ASP.NET Core configuration and dependency injection or .NET console application structure.
  • Basic identity, role assignment, encryption, TLS, environment, and deployment concepts.
  • Awareness of Git history, CI/CD artifacts, logs, backups, and process environment exposure.
  • A .NET 10 SDK to run the dependency-free rotation sample.

When to use Secrets Management

Good fit

  • Use workload identity or federation when a platform can issue short-lived credentials directly to the workload.
  • Use a managed vault for remaining application secrets that require controlled retrieval, audit, versioning, and rotation.
  • Use local user-secrets or an approved developer vault only for development values that never enter source.
  • Use certificates or asymmetric keys when verification can occur without sharing private material.

Choose another approach when

  • Do not store secrets in source, appsettings, container images, client applications, IaC state, pipeline arguments, or generated artifacts.
  • Do not put ordinary nonsecret configuration into a vault without a security reason.
  • Do not use one broad master credential or shared vault identity across unrelated workloads and environments.
  • Do not pin an unversioned secret forever in process memory when rotation is required.

Key concepts

Centralized storage and access control

A dedicated secrets store lets access be granted, audited, and revoked per identity, instead of secrets being copied into every environment's configuration.

Workload identity

Letting a compute resource authenticate to the secrets store using its platform identity removes the need for a bootstrap credential to fetch other credentials.

Rotation

Regularly replacing secrets, ideally automatically, limits how long a leaked or compromised credential remains valid.

Least privilege scoping

An application or service should only be able to read the specific secrets it needs, not every secret in a shared vault.

Secret elimination

Managed identity, workload federation, platform connectors, and asymmetric designs remove long-lived shared values and reduce rotation burden.

Versioning and overlap

New versions allow safe rollout while old and new credentials overlap until every consumer adopts the replacement and rollback risk passes.

Caching and refresh

A bounded cache reduces vault latency and throttling while a refresh policy prevents a running process from holding obsolete credentials indefinitely.

Detection and incident response

Secret scanning, vault audit logs, redaction, anomaly alerts, ownership, revocation, and recovery procedures limit exposure impact.

Architecture

A workload obtains a short-lived platform identity, passes network and identity policy, retrieves only authorized current secret versions, uses a bounded in-process cache, and refreshes during controlled rotation while audit, scanning, alerting, recovery, and revocation cover the lifecycle.

Workload identity
Network boundary
Vault RBAC
Versioned secret
Bounded cache
Dependent service
Audit + alerts
Rotation + revocation

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated sample models the application-side lifecycle without a cloud dependency: versioned lookup, short-lived caching, rotation adoption without restart, deterministic time, redacted diagnostics, and failure when a required secret is absent.

  1. 01
    Inventory and classify

    Find credentials across code, configuration, repositories, pipelines, artifacts, hosts, and third parties; assign owners and consumers.

  2. 02
    Eliminate what you can

    Replace shared credentials with managed identity, federation, certificates, or service-native authorization.

  3. 03
    Create vault boundaries

    Separate environments and applications, configure least-privilege data access, private networking where needed, audit, soft delete, and purge protection.

  4. 04
    Integrate through identity

    Use the workload's platform credential and inject a narrow provider rather than distributing a bootstrap secret.

  5. 05
    Cache and redact

    Cache values briefly, keep them out of logs and exceptions, expose only version or age metadata, and clear unnecessary copies.

  6. 06
    Rotate safely

    Create a new version, overlap validity, refresh consumers, verify adoption, retain rollback briefly, then revoke the old value.

  7. 07
    Detect and respond

    Scan repositories and pipelines, alert on unusual reads, rotate immediately after exposure, investigate use, and document recovery.

Code example

The application authenticates to the vault using its managed identity, with no credential stored in configuration to reach it.

SecretsSetup.cs
var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddAzureKeyVault(
    new Uri("https://orders-vault.vault.azure.net/"),
    new DefaultAzureCredential());

var app = builder.Build();
var connectionString = app.Configuration["OrdersDb--ConnectionString"];

Testing strategy

Tests should prove lifecycle behavior with synthetic values and fake providers, never real production credentials.

  • Use a provider abstraction and deterministic TimeProvider to test cache hit, expiry, refresh, missing value, cancellation, and vault failure.
  • Prove a new version is adopted without restart after the configured cache interval.
  • Assert exceptions, ToString, logs, traces, snapshots, and test failure output never contain secret values.
  • Integration-test identity and vault access in an isolated environment with least-privilege roles and disposable synthetic secrets.
  • Rehearse rotation overlap, rollback, revocation, deleted-value recovery, and compromised-credential response.

Security considerations

The vault, workload identity, runtime process, administrators, delivery system, and dependent service form one end-to-end secret boundary.

  • Prefer managed identity or federation and narrowly scope data-plane roles per application and environment.
  • Restrict network access, enable audit, soft delete, purge protection, and alerts for unusual reads or administrative changes.
  • Never emit values to source, configuration artifacts, command lines, logs, exceptions, traces, crash dumps, support bundles, or client responses.
  • Separate secret readers, writers, rotators, and administrators and use just-in-time privileged access.
  • Rotate immediately after suspected exposure and investigate usage; deleting a repository line is not remediation.

Performance and scalability

Vault calls are remote and rate-limited, so safe caching improves reliability while overly long caching prevents rotation.

  • Cache with a bounded TTL based on rotation and revocation requirements and add jitter to large-fleet refresh.
  • Avoid loading entire vaults; request only the values required by the current workload.
  • Reuse supported clients, propagate cancellation, bound timeouts, and observe throttling without logging names that reveal sensitive architecture unnecessarily.
  • Use versionless lookup for current credentials when automatic adoption is intended and versioned identifiers where decrypting historic data requires stable material.
  • Do not place vault access on a hot per-record path when a safe process-level cache is sufficient.

Deployment and operations

Secret management succeeds only when infrastructure, identity, application refresh, dependent systems, and incident operations agree on the lifecycle.

  • Provision vault, identity, roles, network controls, diagnostics, recovery, expiration, and rotation policy through reviewed infrastructure as code.
  • Keep development, test, staging, and production stores and identities isolated.
  • Validate configuration contains only vault identifiers and nonsecret metadata, never resolved values.
  • Roll credentials through overlapping versions, monitor consumer adoption, and revoke the old value after verification.
  • Include secret scanning, dependency inventory, runtime identity smoke tests, rollback, and emergency rotation in release procedures.

Common problems and fixes

The workload cannot read a secret.

Likely cause: Identity selection, data-plane role, network policy, name mapping, disabled version, or environment configuration is wrong.

Fix: Verify the actual workload principal, narrow role assignment, network path, object state, and safe audit logs.

A rotated credential is not adopted.

Likely cause: The application pinned a version or cached indefinitely.

Fix: Use deliberate versionless lookup, bounded refresh, adoption telemetry, and a rotation integration test.

Rotation breaks some instances.

Likely cause: The old credential was revoked before every consumer refreshed or the dependency lacked overlap.

Fix: Use two-version overlap, observe fleet adoption, retain rollback, and revoke only after verification.

A secret appears in logs or CI.

Likely cause: Commands, configuration dumps, exception messages, test output, or telemetry captured the value.

Fix: Revoke and rotate immediately, remove and restrict artifacts, investigate access, and add centralized redaction and scanning.

Vault traffic spikes at deployment.

Likely cause: Every instance refreshes all values simultaneously or retrieves per request.

Fix: Use narrow bounded caches, client reuse, jittered refresh, and capacity-aware rollout.

Deleted secret recovery is impossible.

Likely cause: Recovery and purge controls or retention were not configured and tested.

Fix: Enable soft delete and purge protection where available and rehearse recovery with owned retention policy.

Best practices

  • Eliminate secrets with workload identity or federation before storing them.
  • Never commit a secret; rotate immediately after any suspected exposure.
  • Separate vaults or strong boundaries by application, region, and environment.
  • Grant each workload only the data operations and objects it needs.
  • Retrieve only required values and cache them for a bounded rotation-aware duration.
  • Redact values from logs, exceptions, telemetry, dumps, commands, and diagnostics.
  • Automate rotation with overlap, adoption verification, rollback, and revocation.
  • Enable scanning, audit, anomaly alerts, recovery protection, and owned incident runbooks.

Production checklist

  • Secrets are inventoried with owner, consumers, environment, purpose, expiry, rotation, and revocation procedure.
  • Long-lived credentials are eliminated through workload identity or federation wherever supported.
  • Vault data roles, administrative roles, networks, environments, audit, recovery, and purge controls are separated.
  • No values appear in source, images, IaC state, pipeline logs, arguments, telemetry, dumps, or client artifacts.
  • Applications retrieve only required values, cache briefly, redact diagnostics, and refresh without restart.
  • Rotation supports version overlap, adoption evidence, rollback, and old-value revocation.
  • Repository and pipeline secret scanning plus unusual-access alerts are enabled and owned.
  • Exposure, vault outage, throttling, deletion recovery, compromised identity, and emergency rotation runbooks are rehearsed.

Common interview questions

Why is committing a secret to source control dangerous even if you delete it in the next commit?

Git history retains every prior version by default, and the secret may already be in forks, backups, CI logs, or cached clones, so deleting it from the latest commit doesn't remove it from anywhere it's already been.

What problem does workload identity solve for secrets management?

Without it, an application needs some credential to authenticate to the secrets store in the first place, which just relocates the original problem; workload identity lets the platform vouch for the application's identity directly, removing that bootstrap credential entirely.

Why rotate secrets that haven't been confirmed as leaked?

You can't always know a secret has leaked—rotation limits the value and window of a leak you don't yet know about, the same way changing a lock periodically doesn't require proof a key was copied.

What is the difference between configuration and a secret?

Configuration controls behavior and is not necessarily confidential; a secret grants access or proves identity and requires restricted storage, use, rotation, and incident handling.

How can an application adopt rotation without restart?

Resolve the current version through a provider, cache it for a bounded time, refresh safely, support overlapping credentials, and observe which version is in use without logging the value.

Why does a vault not prevent every leak?

Authorized workloads and administrators can retrieve values, and those values can still escape through logs, exceptions, dumps, process access, or overbroad permissions.

What should happen after a secret is committed to Git?

Revoke and rotate it immediately, investigate where it propagated and whether it was used, restrict or remove exposed artifacts, then improve scanning and process controls.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Secrets Rotation

A dependency-free .NET 10 sample demonstrating secret-provider boundaries, versioned lookup, bounded caching, rotation without restart, deterministic time, redacted diagnostics, and failure-safe tests.

.NET 10TimeProviderSecrets ManagementxUnit
dedicated-samplerotationredactionbounded-cachetesting
Run
dotnet run --project src/SecretsRotation
Test
dotnet test SecretsRotation.slnx