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:
Database connections
Storage accounts
Third-party APIs
SMTP servers
Payment gateways
JWT signing keys
Certificates
Hardcoding secrets creates several problems:
Source code exposure
Difficult credential updates
Shared credentials across environments
Increased security risks
Manual deployment changes
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:
Secrets
Encryption keys
Certificates
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:
Visual Studio
Azure CLI
Managed Identity
Environment variables
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:
No stored passwords
Automatic credential management
Reduced attack surface
Easier secret rotation
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:
Create a new secret version.
Update the dependent service.
Verify application connectivity.
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:
Load secrets during startup.
Cache frequently accessed values.
Refresh them periodically if required.
This reduces latency and avoids unnecessary requests to Key Vault.
Configuration by Environment
Different environments typically use different Key Vault instances.
Example:
| Environment | Key Vault |
|---|---|
| Development | Dev Key Vault |
| Testing | Test Key Vault |
| Production | Production 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:
Application starts.
Azure authenticates the application.
Key Vault permissions are verified.
Secret is retrieved.
Configuration is updated.
Database or external service is accessed.
Secret remains securely managed outside the application.
This approach keeps sensitive values out of source code and deployment packages.
Secret Management Comparison
| Storage Method | Security | Rotation | Recommended |
|---|---|---|---|
| Source code | Poor | Manual | No |
| appsettings.json | Low | Manual | Development only |
| Environment Variables | Moderate | Manual | Limited scenarios |
| Azure Key Vault | Excellent | Supported | Yes |
| Managed Identity + Key Vault | Excellent | Supported | Best 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
Store all sensitive values in Azure Key Vault.
Use Managed Identity whenever possible.
Avoid hardcoded credentials.
Separate Key Vaults by environment.
Grant least-privilege access.
Rotate secrets regularly.
Monitor Key Vault access logs.
Keep secret names meaningful and consistent.
Common Mistakes
| Mistake | Impact |
|---|---|
| Hardcoding secrets | Security risk |
| Sharing one Key Vault across all environments | Increased operational risk |
| Using expired credentials | Application failures |
| Granting excessive permissions | Larger attack surface |
| Requesting secrets on every API call | Increased latency |
| Ignoring access monitoring | Delayed detection of issues |
Troubleshooting
Secret Cannot Be Retrieved
Verify:
Key Vault URL
Secret name
Azure authentication
Managed Identity configuration
Access permissions
Authentication Fails
Check:
Azure login status during development
Managed Identity assignment
Role assignments or Key Vault access policies
Network connectivity
Application Uses an Old Secret
Review:
Secret version
Application restart requirements
Configuration caching
Rotation process
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.
Join the conversation! Your thoughts help the community grow.