Applications often require secrets such as database connection strings, API keys, certificates, and authentication tokens. Storing these values in configuration files or source code increases the risk of accidental exposure and makes credential management difficult.

Azure Key Vault provides a centralized and secure way to store, manage, and rotate secrets. Combined with .NET configuration providers, applications can retrieve secrets at runtime without embedding sensitive information in the codebase.

In this article, you'll learn how to integrate Azure Key Vault with a .NET application, implement secure secret rotation, and follow production-ready practices for managing application secrets.

Why Secret Management Matters

Applications commonly require secrets for:

Hardcoding secrets creates several problems:

A centralized secret management solution simplifies both security and operations.

What Is Azure Key Vault?

Azure Key Vault is a managed service for storing and managing:

Instead of storing credentials in appsettings.json, the application retrieves them securely at runtime.

A simplified architecture looks like this:

ASP.NET Core App
        │
        ▼
Managed Identity
        │
        ▼
Azure Key Vault
        │
        ▼
Database / External Services

The application authenticates with Azure and requests only the secrets it is authorized to access.

Project Setup

Create a new ASP.NET Core Web API.

dotnet new webapi -n KeyVaultDemo

Install the required packages.

dotnet add package Azure.Identity
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets

These packages enable Azure authentication and Key Vault integration with the .NET configuration system.

Configure Azure Key Vault

Register Azure Key Vault during application startup.

using Azure.Identity;

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

app.Run();

Why Use DefaultAzureCredential?

DefaultAzureCredential automatically selects the most appropriate authentication method based on the execution environment.

For example:

This simplifies development while supporting secure production authentication.

Store a Secret

Suppose a Key Vault secret is named:

SqlConnectionString

Retrieve it like any other configuration value.

var connectionString =
    builder.Configuration["SqlConnectionString"];

No connection string is required inside appsettings.json.

Configure EF Core

Use the retrieved secret.

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(
        builder.Configuration["SqlConnectionString"]);
});

The application now reads the connection string directly from Azure Key Vault.

Using Managed Identity

Applications running in Azure should use Managed Identity instead of client secrets.

Authentication occurs automatically.

var credential = new DefaultAzureCredential();

Benefits include:

Managed Identity is the recommended authentication mechanism for Azure-hosted applications.

Secret Rotation

Secret rotation replaces existing credentials with new values on a regular basis.

Typical rotation process:

  1. Create a new secret version.

  2. Update the dependent service.

  3. Verify application connectivity.

  4. Remove old credentials when no longer needed.

Applications continue using the secret name rather than a specific version.

Example:

SqlConnectionString
      │
      ├── Version 1
      ├── Version 2
      └── Version 3

The application always requests the latest active version.

Accessing Secrets with SecretClient

Some applications retrieve secrets programmatically.

using Azure.Security.KeyVault.Secrets;

var client = new SecretClient(
    new Uri("https://your-keyvault.vault.azure.net/"),
    new DefaultAzureCredential());

KeyVaultSecret secret =
    await client.GetSecretAsync("SqlConnectionString");

Console.WriteLine(secret.Value);

This approach is useful when secrets need to be retrieved dynamically rather than through configuration.

Caching Secrets

Avoid requesting secrets for every HTTP request.

Instead:

This reduces latency and avoids unnecessary requests to Key Vault.

Configuration by Environment

Different environments typically use different Key Vault instances.

Example:

EnvironmentKey Vault
DevelopmentDev Key Vault
TestingTest Key Vault
ProductionProduction Key Vault

Keeping environments isolated reduces the risk of accidentally exposing production credentials.

End-to-End Secret Flow

A production request typically follows these steps:

  1. Application starts.

  2. Azure authenticates the application.

  3. Key Vault permissions are verified.

  4. Secret is retrieved.

  5. Configuration is updated.

  6. Database or external service is accessed.

  7. Secret remains securely managed outside the application.

This approach keeps sensitive values out of source code and deployment packages.

Secret Management Comparison

Storage MethodSecurityRotationRecommended
Source codePoorManualNo
appsettings.jsonLowManualDevelopment only
Environment VariablesModerateManualLimited scenarios
Azure Key VaultExcellentSupportedYes
Managed Identity + Key VaultExcellentSupportedBest Practice

Secret Rotation Strategy

A secure rotation process should include:

Rotate Regularly

Rotate credentials according to your organization's security policies or compliance requirements.

Version Secrets

Create new secret versions instead of modifying existing values. This supports gradual rollout and easier rollback.

Validate Before Removing Old Secrets

Ensure applications have successfully adopted the new credentials before disabling or deleting previous versions.

Monitor Secret Access

Review access logs and monitor failed authentication attempts to detect configuration issues or unauthorized access.

Best Practices

Common Mistakes

MistakeImpact
Hardcoding secretsSecurity risk
Sharing one Key Vault across all environmentsIncreased operational risk
Using expired credentialsApplication failures
Granting excessive permissionsLarger attack surface
Requesting secrets on every API callIncreased latency
Ignoring access monitoringDelayed detection of issues

Troubleshooting

Secret Cannot Be Retrieved

Verify:

Authentication Fails

Check:

Application Uses an Old Secret

Review:

Ensure the application is configured to use the latest active secret version.

FAQs

Why should I use Azure Key Vault?

It provides centralized, secure storage for secrets while reducing the need to store sensitive information in source code or configuration files.

What is Managed Identity?

Managed Identity is an Azure feature that allows applications to authenticate securely without storing credentials.

Can I rotate secrets without changing my application code?

Yes. Applications typically reference the secret name, while Azure Key Vault manages multiple versions behind the scenes.

Should I cache secrets?

Yes. Frequently requesting secrets from Key Vault can increase latency. Cache values appropriately and refresh them based on your rotation strategy.

Can Azure Key Vault store certificates?

Yes. In addition to secrets, Azure Key Vault securely stores certificates and cryptographic keys.

Conclusion

Secure secret management is a fundamental part of building production-ready .NET applications. Azure Key Vault provides a centralized solution for storing sensitive information, while Managed Identity eliminates the need to embed credentials in application code or configuration files.

By combining secure storage, controlled access, versioned secrets, and a well-defined rotation strategy, you can reduce operational risk, simplify credential management, and strengthen the overall security of your applications.