| Azure-Cognitive-Services :👈 | 👉:Azure-SQL |
Azure Key Vault |
Azure Key Vault - Complete Guide
1. What is Azure Key Vault?
Azure Key Vault is a security service in Microsoft Azure used to securely store, manage, access, and control sensitive application information such as passwords, database connection strings, API keys, certificates, and encryption keys.
Instead of storing sensitive information directly in application configuration files, applications retrieve the required secrets securely from Azure Key Vault.
Problems with Storing Secrets in appsettings.json
- Developers might accidentally commit credentials to Git.
- Anyone with access to configuration files might see passwords.
- Credentials might be exposed through deployment packages.
- Changing passwords requires updating application configuration.
- Different environments require different credentials.
Main Features of Azure Key Vault
| Feature | Purpose | Examples |
|---|---|---|
| Secrets | Store sensitive text values | Passwords, API keys, connection strings |
| Keys | Manage cryptographic keys | Encryption and decryption |
| Certificates | Manage digital certificates | SSL/TLS certificates |
Core Capabilities
- Secure Storage: Secrets are stored in hardware security modules (HSMs).
- Secrets Management: Store and manage sensitive data like connection strings, API keys, and credentials.
- Key Management: Create and control encryption keys used to encrypt data.
- Certificate Management: Provision, manage, and deploy TLS/SSL certificates automatically.
- Access Control: Integrated with Azure Active Directory (Azure AD) to ensure only authorized applications and users can access data.
- Scalability: Automatically scales with application needs.
- Centralized Management: Manage secrets across multiple apps from one place.
- Auditing: Integrated with Azure Monitor and logging tools.
- Logging and Monitoring: Integrates with Azure Monitor and Azure Security Center to track usage and detect threats.
Why Use Azure Key Vault?
- Centralized storage for application secrets.
- Improved security by eliminating the need to store secrets in code or configuration files.
- Compliance with industry standards and regulations.
- Easy integration with Azure services, DevOps pipelines, and applications.
Example: Storing and Retrieving a Secret in C#
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
class Program
{
static void Main(string[] args)
{
// Replace with your Key Vault URL
string keyVaultUrl = "https://<YourKeyVaultName>.vault.azure.net/";
var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
// Set a secret
client.SetSecret("MySecretKey", "SuperSecretValue123");
// Retrieve the secret
KeyVaultSecret secret = client.GetSecret("MySecretKey");
Console.WriteLine($"Secret Value: {secret.Value}");
}
}
How This Works
- Authentication: The app authenticates to Key Vault using Azure AD and a managed identity or service principal.
- Set Secret: Stores "MySecretKey" with the value "SuperSecretValue123".
- Get Secret: Retrieves the value securely when needed by the application.
Typical Use Cases
- Securely storing API keys, database connection strings, or credentials.
- Managing SSL certificates for web apps
- Managing encryption keys for sensitive data.
- Automating certificate renewal and deployment for web applications.
- Integrating with CI/CD pipelines for secret management in DevOps.
2. Understanding the Three Main Components
2.1 Secrets
A secret is a sensitive text value stored securely in Key Vault.
Examples:
- SQL Server passwords
- API keys
- Third-party service credentials
- Storage account connection strings
- Application configuration values
Example secret:
Name: DatabaseConnectionString
Value:
Server=myserver.database.windows.net;
Database=MyDB;
User ID=myuser;
Password=MyPassword;
Your application retrieves the secret when required. A secret is not automatically an encrypted database connection mechanism. It is a secure place to store and retrieve the sensitive value.
2.2 Keys
Keys are cryptographic objects used for security operations.
- Encrypting sensitive data.
- Decrypting encrypted information.
- Creating digital signatures.
- Verifying digital signatures.
- Protecting encryption keys used by other Azure services.
Azure Key Vault can perform cryptographic operations without exposing private key material to your application.
2.3 Certificates
Certificates are used to establish trust and verify identities.
- HTTPS communication.
- SSL/TLS authentication.
- Client certificate authentication.
- Application-to-application authentication.
3. Azure Key Vault Architecture
Consider a typical ASP.NET Core application architecture:
Communication Flow
- An ASP.NET Core application is deployed to Azure App Service.
- The application has a Managed Identity.
- The application requests access to Azure Key Vault.
- Azure authenticates the Managed Identity.
- Key Vault checks its authorization permissions.
- If authorized, Key Vault returns the requested secret.
- The application uses the secret to connect to a database or external service.
The application does not need to store a separate Key Vault username or password when using Managed Identity.
4. Azure Key Vault vs appsettings.json vs Azure App Configuration
| Feature | appsettings.json | Azure Key Vault | Azure App Configuration |
|---|---|---|---|
| Normal application settings | Yes | Possible, but not ideal | Yes |
| Password storage | No | Yes | Not recommended |
| API keys | No | Yes | Not recommended |
| Encryption keys | No | Yes | No |
| Certificates | No | Yes | No |
| Feature flags | Basic implementation | No | Yes |
| Centralized configuration | Limited | Secrets-focused | Yes |
Recommended Architecture
- appsettings.json: Non-sensitive default settings.
- Azure App Configuration: Centralized application configuration and feature flags.
- Azure Key Vault: Passwords, API keys, certificates, and sensitive values.
5. Step-by-Step: Create Azure Key Vault
Step 1: Create a Key Vault
- Log in to the Azure Portal.
- Search for Key Vaults.
- Select Create.
- Select your Azure subscription.
- Select your resource group.
- Enter a unique Key Vault name.
- Select your deployment region.
- Configure pricing and other required settings.
- Configure the permission model.
- Review and create.
Example configuration:
Key Vault Name: mycompany-kv
Resource Group: mycompany-rg
Region: Central India
Pricing: Standard
Key Vault names must be globally unique.
Step 2: Configure Access Permissions
Azure Key Vault supports two main authorization approaches.
A. Azure RBAC
Azure Role-Based Access Control allows you to assign specific permissions to users, groups, and application identities.
| Role | Responsibility |
|---|---|
| Key Vault Reader | Read vault metadata, not secret values. |
| Key Vault Secrets User | Read secret contents. |
| Key Vault Secrets Officer | Manage secrets. |
| Key Vault Administrator | Manage all Key Vault data-plane objects. |
Azure RBAC is generally the preferred authorization model for new deployments.
B. Vault Access Policies
Access policies provide a separate permission model for controlling access to secrets, keys, and certificates.
Step 3: Create a Secret
- Open your Key Vault.
- Select Secrets.
- Select Generate/Import.
- Enter the secret name.
- Enter the secret value.
- Select Create.
Example:
Name: DatabaseConnectionString
Value:
Server=myserver.database.windows.net;
Database=MyDB;
User ID=myuser;
Password=MyPassword;
Other secret examples:
- PaymentApiKey
- EmailServiceApiKey
- JwtSigningSecret
- RedisConnectionString
- ExternalServicePassword
Never use real credentials in source-code examples or public repositories.
6. Connect Azure Key Vault with ASP.NET Core
There are two common ways to integrate Key Vault with .NET:
- Azure Key Vault Configuration Provider - loads secrets into ASP.NET Core configuration.
- Azure Key Vault SDK - retrieves secrets programmatically using SecretClient.
6.1 Install NuGet Packages
For ASP.NET Core configuration integration:
dotnet add package Azure.Identity
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
For direct secret management:
dotnet add package Azure.Security.KeyVault.Secrets
| Package | Responsibility |
|---|---|
| Azure.Identity | Authentication using Managed Identity and DefaultAzureCredential. |
| Azure.Extensions.AspNetCore.Configuration.Secrets | Loads Key Vault secrets into IConfiguration. |
| Azure.Security.KeyVault.Secrets | Directly creates, reads, updates, and deletes secrets. |
6.2 Configure Local Development Authentication
During development, authenticate through Azure CLI:
az login
Select the correct subscription:
az account set --subscription "YourSubscriptionId"
Your developer account must have the required Key Vault data-plane permissions. For example, assign Key Vault Secrets User.
6.3 Configure Azure Key Vault in Program.cs
This approach makes Key Vault secrets available through IConfiguration.
Program.cs
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
var keyVaultUrl =
builder.Configuration["KeyVault:VaultUri"];
if (!string.IsNullOrWhiteSpace(keyVaultUrl))
{
builder.Configuration.AddAzureKeyVault(
new Uri(keyVaultUrl),
new DefaultAzureCredential());
}
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
appsettings.json
{
"KeyVault": {
"VaultUri": "https://mycompany-kv.vault.azure.net/"
}
}
Notice that we are storing only the Key Vault URL in appsettings.json, not the actual secret values.
DefaultAzureCredential automatically attempts supported authentication methods based on the available environment.
- Local development: Azure CLI credentials.
- Azure App Service: Managed Identity.
- Azure Virtual Machines: Managed Identity.
- Azure-hosted workloads: Supported workload identity configurations.
6.4 Access the Secret Using IConfiguration
Suppose you created the following secret in Key Vault:
DatabaseConnectionString
Retrieve it using:
var connectionString =
builder.Configuration["DatabaseConnectionString"];
Use it in dependency injection:
builder.Services.AddDbContext<AppDbContext>(options =>
{
var connectionString =
builder.Configuration["DatabaseConnectionString"];
options.UseSqlServer(connectionString);
});
Alternatively, use the standard connection-string configuration convention.
Secret name:
ConnectionStrings--DefaultConnection
The double hyphen (--) is interpreted as a colon (:) by the Azure Key Vault configuration provider.
Access it using:
builder.Configuration.GetConnectionString(
"DefaultConnection");
6.5 Configure Managed Identity in Azure App Service
- Open your Azure App Service.
- Navigate to Settings.
- Select Identity.
- Open the System assigned tab.
- Change Status to On.
- Select Save.
- Azure creates an identity for your application.
Now assign permission to that identity:
- Open your Key Vault.
- Navigate to Access control (IAM).
- Select Add role assignment.
- Select Key Vault Secrets User.
- Select Managed Identity as the member type.
- Select your App Service.
- Review and assign.
Your App Service can now authenticate to Key Vault without storing a client secret.
Important distinction:
- Authentication: Who is accessing Key Vault?
- Authorization: What is that identity allowed to access?
Managed Identity handles authentication. Azure RBAC controls authorization.
6.6 System-Assigned vs User-Assigned Managed Identity
| Feature | System-assigned | User-assigned |
|---|---|---|
| Lifecycle | Linked to Azure resource | Independent resource |
| Creation | Enabled on resource | Created separately |
| Deletion | Deleted with resource | Remains until deleted |
| Sharing | One resource identity | Can be shared across resources |
| Management | Simpler | More control |
Use System-assigned Managed Identity when:
- One App Service accesses Key Vault.
- You want simple identity management.
- The identity should be removed when the App Service is deleted.
Use User-assigned Managed Identity when:
- Multiple Azure resources need the same identity.
- You want identity lifecycle independent of application deployment.
- You need consistent identity permissions across deployments.
7. Using Azure Key Vault SDK Directly
Sometimes you do not want to load all secrets into IConfiguration. You may want to retrieve a particular secret when a service needs it. For this, use SecretClient.
Example 1: Retrieve a Secret
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var vaultUri = new Uri(
"https://mycompany-kv.vault.azure.net/");
var client = new SecretClient(
vaultUri,
new DefaultAzureCredential());
KeyVaultSecret secret =
await client.GetSecretAsync("PaymentApiKey");
string apiKey = secret.Value;
Example 2: Create a Secret
await client.SetSecretAsync(
"PaymentApiKey",
"your-api-key-value");
If a secret with the same name already exists, this creates a new version rather than replacing the historical version.
Example 3: Update a Secret
await client.SetSecretAsync(
"PaymentApiKey",
"new-api-key-value");
Example 4: Delete a Secret
await client.StartDeleteSecretAsync(
"PaymentApiKey");
With soft delete enabled, the deleted secret remains recoverable during its retention period.
Example 5: Retrieve Secret Metadata
KeyVaultSecret secret =
await client.GetSecretAsync("PaymentApiKey");
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Properties.Version);
Console.WriteLine(secret.Properties.Enabled);
Avoid printing the actual secret value in logs.
Example 6: Use Dependency Injection
Register SecretClient once:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var builder = WebApplication.CreateBuilder(args);
var vaultUri = new Uri(
builder.Configuration["KeyVault:VaultUri"]!);
builder.Services.AddSingleton(
new SecretClient(
vaultUri,
new DefaultAzureCredential()));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Inject it wherever required:
public class PaymentService
{
private readonly SecretClient _secretClient;
public PaymentService(SecretClient secretClient)
{
_secretClient = secretClient;
}
public async Task<string> GetApiKeyAsync()
{
var secret = await _secretClient.GetSecretAsync(
"PaymentApiKey");
return secret.Value.Value;
}
}
Pro Tip: Reuse SDK clients. They are designed to be thread-safe and reused. Avoid constructing a new client for every HTTP request.
8. Azure Key Vault with Entity Framework Core
Consider an ASP.NET Core application using:
- ASP.NET Core Web API
- Entity Framework Core
- SQL Server
- Azure Key Vault
- Azure App Service
Step 1: Store the Database Connection String in Key Vault
ConnectionStrings--DefaultConnection
Step 2: Add the Key Vault Configuration Provider
builder.Configuration.AddAzureKeyVault(
new Uri(
builder.Configuration["KeyVault:VaultUri"]!),
new DefaultAzureCredential());
Step 3: Register DbContext
builder.Services.AddDbContext<AppDbContext>(
options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection"));
});
Step 4: Deploy to Azure App Service
Enable Managed Identity and assign Key Vault Secrets User. The application can now retrieve the database connection string without storing its password in source code.
Better Production Approach: For Azure SQL Database, consider Microsoft Entra authentication with Managed Identity instead of a SQL username and password. This can eliminate the database password secret entirely.
9. Azure Key Vault with Different Deployment Environments
A common mistake is using one Key Vault for development, testing, staging, and production.
Development:
Key Vault: myapp-dev-kv
Development database credentials
Test API keys
Development service credentials
Staging:
Key Vault: myapp-staging-kv
Staging database credentials
Pre-production API keys
Staging service credentials
Production:
Key Vault: myapp-prod-kv
Production database credentials
Live service credentials
Production API keys
Benefits
- Better security isolation.
- Reduced impact if one environment is compromised.
- Independent access permissions.
- Easier secret rotation.
- Reduced risk of accidentally using production credentials during development.
10. Azure Key Vault Security Best Practices
10.1 Use Managed Identity Instead of Client Secrets
Avoid:
var credential = new ClientSecretCredential(
tenantId,
clientId,
"hardcoded-client-secret");
Why?
- Client secrets must be stored somewhere.
- They can accidentally be committed to Git.
- They need rotation.
- Anyone who obtains them might impersonate the application.
Prefer:
var credential = new DefaultAzureCredential();
In production, use Managed Identity.
10.2 Follow the Principle of Least Privilege
Never give every application administrator-level access.
| Identity | Required Permission |
|---|---|
| Web API | Read secrets |
| Deployment pipeline | Only required deployment permissions |
| Security administrator | Manage security configuration |
| Certificate automation | Manage certificates |
| Developer | Access development secrets only |
For an application that only needs to retrieve secrets, assign Key Vault Secrets User.
10.3 Enable Soft Delete
Soft Delete protects against accidental deletion.
Secret: DatabasePassword
Status: Deleted
Recovery: Available
You can recover a deleted secret during the configured retention period. The retention period can be configured between 7 and 90 days.
10.4 Enable Purge Protection
Purge Protection adds another security layer.
| Feature | Soft Delete | Purge Protection |
|---|---|---|
| Recover deleted secrets | Yes | Works with soft delete |
| Protect against permanent deletion | No, not by itself | Yes |
| Protect against malicious deletion | Partially | Stronger protection |
For production, enable both.
10.5 Restrict Network Access
Use:
- Private Endpoints.
- Azure Virtual Network integration.
- Key Vault firewall rules.
- Private DNS configuration.
- Restricted public network access.
Benefits:
- Reduces exposure to public networks.
- Supports private network architecture.
- Helps meet enterprise security requirements.
Creating a Private Endpoint alone is not enough. Configure DNS resolution, application network connectivity, and Key Vault public network access appropriately.
10.6 Enable Logging and Monitoring
You should know:
- Who accessed Key Vault.
- Which secrets were accessed.
- When access occurred.
- Whether access failed.
- Whether secrets were created, updated, or deleted.
- Whether unusual access patterns occurred.
Configure:
- Azure Key Vault diagnostic settings.
- Azure Monitor.
- Log Analytics workspace.
- Azure Monitor alerts.
- Microsoft Defender for Key Vault, where appropriate.
| Event | Suggested Action |
|---|---|
| Multiple failed authentication attempts | Investigate identity |
| Unexpected secret deletion | Notify security team |
| New administrator role assignment | Audit assignment |
| Unusual secret access | Investigate access pattern |
| Certificate nearing expiry | Notify certificate owner |
Never log the actual secret value.
10.7 Rotate Secrets Regularly
A good rotation process:
- Generate a new credential.
- Update the target service to accept it.
- Update the Key Vault secret.
- Refresh the application's cached configuration or connection.
- Verify successful connections.
- Revoke the old credential.
For services that support two active credentials, use overlapping credentials to avoid downtime.
Updating a Key Vault secret does not automatically update values already loaded into application memory or existing database connections. Design the refresh and reconnection process explicitly.
10.8 Separate Permissions for Administrators and Applications
- Developers can read development secrets.
- Production applications can read only their production secrets.
- Security administrators manage permissions.
- Deployment identities have limited deployment privileges.
- No ordinary application identity can delete the production vault.
11. Performance Optimization
Azure Key Vault is a security service, not a high-speed configuration database. Calling it repeatedly for every HTTP request is a poor design.
11.1 Avoid Calling Key Vault on Every Request
Bad Implementation:
public async Task<IActionResult> Get()
{
var secret = await _secretClient.GetSecretAsync(
"PaymentApiKey");
// Process request
return Ok();
}
If your API receives 1,000 requests per minute and every request retrieves the same secret, you generate 1,000 Key Vault requests per minute.
This can increase:
- Network latency.
- Azure service consumption.
- API response time.
- Risk of throttling.
- Dependency on Key Vault availability.
11.2 Cache Secrets in Memory
A better approach is to retrieve the secret once and reuse it.
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Caching.Memory;
public class SecretService
{
private readonly SecretClient _client;
private readonly IMemoryCache _cache;
public SecretService(
SecretClient client,
IMemoryCache cache)
{
_client = client;
_cache = cache;
}
public async Task<string> GetSecretAsync(
string secretName)
{
return await _cache.GetOrCreateAsync(
secretName,
async entry =>
{
entry.AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(15);
var secret = await _client.GetSecretAsync(
secretName);
return secret.Value.Value;
}) ?? string.Empty;
}
}
Register the cache:
builder.Services.AddMemoryCache();
Register your service:
builder.Services.AddSingleton<SecretService>();
This example caches secrets for 15 minutes. Choose the cache duration based on your secret rotation policy and risk requirements.
Important:
- IMemoryCache is local to one application instance.
- It is not shared across multiple instances.
- Production code should handle failures, cancellation, cache refresh, and concurrent refreshes carefully.
- Never silently fall back to hardcoded production credentials.
11.3 Implement Retry with Exponential Backoff
Key Vault may occasionally return transient errors or throttling responses. Instead of retrying immediately, progressively increase the delay.
First attempt: Immediately
Second attempt: Wait 1 second
Third attempt: Wait 2 seconds
Fourth attempt: Wait 4 seconds
Use retry policies provided by the Azure SDK where possible.
var options = new SecretClientOptions();
options.Retry.MaxRetries = 5;
options.Retry.Delay =
TimeSpan.FromSeconds(1);
options.Retry.MaxDelay =
TimeSpan.FromSeconds(10);
var client = new SecretClient(
vaultUri,
new DefaultAzureCredential(),
options);
Avoid infinite retries. Also respect server-provided retry guidance for throttling responses.
11.4 Reuse SecretClient
Avoid:
public async Task<string> GetSecret()
{
var client = new SecretClient(
vaultUri,
new DefaultAzureCredential());
// Retrieve secret
}
Prefer registering SecretClient once using dependency injection.
Benefits:
- Reuses underlying HTTP resources.
- Reduces unnecessary object creation.
- Simplifies testing.
- Improves maintainability.
11.5 Avoid Storing Unnecessary Secrets
Do not store every configuration value in Key Vault.
ApplicationName
PageSize
EnableLogging
MaximumRetryCount
Theme
These are normal application settings, not secrets. Use Azure App Configuration or ordinary application configuration for such values.
11.6 Understand Configuration Loading
builder.Configuration.AddAzureKeyVault(
vaultUri,
new DefaultAzureCredential());
The provider retrieves secrets while building the application configuration. Do not assume that changing a secret in Key Vault immediately changes the value in a running application.
If you require automatic refresh, design an explicit refresh mechanism or use a supported configuration-refresh integration.
12. What NOT to Do with Azure Key Vault
| Avoid | Why | Better Approach |
|---|---|---|
| Hardcoding passwords | Exposes credentials | Key Vault |
| Storing secrets in Git | Repository exposure | Key Vault |
| Using one vault for every environment | Larger security impact | Separate vaults |
| Giving Administrator permissions to APIs | Excessive privileges | Secrets User |
| Calling Key Vault on every request | Performance overhead | Memory caching |
| Logging secret values | Sensitive data exposure | Log metadata only |
| Disabling purge protection | Data-loss risk | Keep enabled |
| Sharing production credentials with developers | Unnecessary exposure | Separate identities |
| Using client secrets unnecessarily | More credentials to manage | Managed Identity |
| Using Key Vault as a database | Not designed for this | SQL, Storage, App Configuration |
| Storing normal settings as secrets | Unnecessary complexity | App Configuration |
| Ignoring secret expiration | Application failures | Rotation and alerts |
| Using the same API key everywhere | Larger compromise impact | Separate credentials |
13. Advanced Concepts Every Experienced Developer Should Know
13.1 Secret Versioning
Every time you update a secret, Key Vault creates a new version.
Secret: DatabasePassword
Version 1: OldPassword
Version 2: NewPassword
Version 3: UpdatedPassword
Benefits:
- Historical version tracking.
- Controlled rollback.
- Easier credential rotation.
- Better auditing.
Retrieve a specific version when required:
var secret = await client.GetSecretAsync(
"DatabasePassword",
"specific-version-id");
Normally, applications should retrieve the current enabled version rather than hardcoding version IDs.
13.2 Secret Expiration
You can configure expiration dates for secrets.
Secret: PaymentApiKey
Created: 01-Nov-2026
Expires: 01-Feb-2027
Benefits:
- Helps enforce credential lifecycle policies.
- Prevents forgotten credentials from remaining valid indefinitely.
- Allows expiry monitoring and alerts.
Key Vault expiration metadata does not necessarily revoke the credential at the external service. You must also manage the credential's validity at the target service.
13.3 Event Grid Integration
Azure Key Vault can publish lifecycle events through Azure Event Grid.
Example events:
- Secret created.
- Secret updated.
- Secret deleted.
- Certificate nearing expiration.
- Certificate expired.
Example workflow:
- A certificate is nearing expiration.
- Key Vault generates an event.
- Event Grid receives the event.
- Azure Function processes the notification.
- The relevant team receives an alert.
- Certificate renewal or replacement is performed.
13.4 Key Vault and Azure DevOps
Never put production passwords directly into Azure DevOps YAML files.
A better approach:
- Create a Key Vault.
- Configure an Azure Resource Manager service connection using workload identity federation where supported.
- Give the pipeline identity only the required Key Vault permissions.
- Retrieve the required secrets during deployment.
- Pass them securely to the deployment process.
- Avoid printing secret values in pipeline logs.
You can also use the Azure Key Vault task in Azure Pipelines.
13.5 Key Vault and Azure Kubernetes Service (AKS)
For applications running in AKS, you can integrate Key Vault using:
- Azure Key Vault provider for Secrets Store CSI Driver.
- Microsoft Entra Workload ID.
- Kubernetes service account federation.
The general flow:
- A pod runs with a Kubernetes service account.
- Workload Identity authenticates the pod.
- The pod receives authorized access to Key Vault.
- The CSI driver retrieves the required secrets.
- Secrets are mounted into the pod as files.
This avoids putting Key Vault credentials directly into Kubernetes manifests.
13.6 Key Vault vs Managed HSM
| Feature | Key Vault | Managed HSM |
|---|---|---|
| Secrets | Yes | No |
| Keys | Yes | Yes |
| Certificates | Yes | No |
| Dedicated HSM security boundary | No | Yes |
| Advanced cryptographic key control | Yes | More specialized |
| Typical usage | Application secrets and keys | High-assurance cryptographic workloads |
Use normal Key Vault for most application secret-management requirements. Consider Managed HSM when regulatory, compliance, or cryptographic isolation requirements justify it.
14. Production-Ready Architecture
Consider an application with:
- ASP.NET Core Web API.
- Azure App Service.
- Azure SQL Database.
- Azure Key Vault.
- Azure App Configuration.
- Microsoft Entra ID.
- Azure Monitor.
- Private Endpoint.
Request Flow
- User sends a request to ASP.NET Core Web API.
- App Service authenticates the user through the application's authentication mechanism.
- The API executes business logic.
- The API uses Entity Framework Core to access Azure SQL.
- Application configuration provides the required connection information.
- Managed Identity provides access to Key Vault when a secret is needed.
- Key Vault returns the authorized secret.
- The application uses the secret without exposing it to the user.
- Azure Monitor collects operational and security information.
Recommended Responsibilities
| Component | Responsibility |
|---|---|
| ASP.NET Core | Application business logic |
| App Service | Application hosting |
| Managed Identity | Passwordless Azure authentication |
| Key Vault | Secrets, keys and certificates |
| App Configuration | Application settings and feature flags |
| Azure SQL | Relational data storage |
| Private Endpoint | Private network connectivity |
| Azure Monitor | Logging and monitoring |
| Microsoft Entra ID | Identity and access management |
15. Advanced Security Checklist
Identity and Access
- Enable Managed Identity.
- Use Azure RBAC.
- Apply least-privilege permissions.
- Separate application and administrator identities.
- Use MFA and PIM for privileged access.
Network Security
- Configure Private Endpoint where appropriate.
- Configure Private DNS correctly.
- Restrict public network access.
- Review firewall and network rules.
Data Protection
- Enable Soft Delete.
- Enable Purge Protection.
- Configure secret expiration.
- Implement automated rotation.
- Back up important cryptographic material.
Monitoring
- Enable diagnostic logging.
- Integrate Azure Monitor and Log Analytics.
- Configure security alerts.
- Monitor secret access failures.
- Audit role assignments regularly.
Application Performance
- Reuse SecretClient.
- Cache secrets appropriately.
- Implement retry with exponential backoff.
- Avoid unnecessary Key Vault calls.
- Design secret refresh and rotation handling.
16. Pro Tips for Experienced Developers
Tip 1: Eliminate Passwords Instead of Just Storing Them Securely
For Azure SQL, use Managed Identity authentication if supported by your architecture. This can remove the need for a database password altogether.
Tip 2: Never Assume Secret Rotation Updates Your Application Automatically
When a secret changes, existing application configuration, cached values, and database connections may still contain the old credential. Plan refresh and reconnection explicitly.
Tip 3: Separate Security Boundaries
Do not put unrelated applications and environments into one large Key Vault. Separation reduces the blast radius of an incident.
Tip 4: Prefer Workload Identity Federation in CI/CD
Where supported, use federated credentials rather than long-lived client secrets for deployment pipelines.
Tip 5: Avoid Excessive Secret Permissions
An application that reads secrets should not be allowed to create, modify, or delete them.
Tip 6: Design for Key Vault Unavailability
Your application should have appropriate timeout, retry, and failure-handling strategies. Cache values where justified, and never silently fall back to hardcoded production credentials.
Tip 7: Treat Secret Values as Sensitive Even After Retrieval
Once a secret enters application memory, it is still sensitive. Avoid logging, returning, serializing, or unnecessarily copying it.
Tip 8: Monitor Expiration Before It Becomes an Outage
Use Azure Monitor and Event Grid notifications to identify certificates and credentials approaching expiration.
Tip 9: Avoid a Single Centralized Vault Becoming a Bottleneck
Use workload-oriented vault boundaries. This can also improve performance and reduce throttling risks.
Tip 10: Use Azure Policy for Governance
Enforce required security settings across your organization's subscriptions instead of relying entirely on developers to configure each vault correctly.
17. Common Azure Key Vault Interview Questions
Basic Questions
1. What is Azure Key Vault?
Azure Key Vault is a cloud service used to securely manage secrets, cryptographic keys, and certificates.
2. What are the three main components of Key Vault?
Secrets, Keys, and Certificates.
3. What is Managed Identity?
Managed Identity is an identity provided by Microsoft Entra ID to Azure resources. It allows applications to authenticate to supported Azure services without managing credentials themselves.
4. What is DefaultAzureCredential?
It is an Azure Identity credential that attempts supported authentication methods based on the execution environment.
5. What is the difference between authentication and authorization?
Authentication verifies identity. Authorization determines what that identity can access.
Intermediate Questions
6. What is the difference between Azure RBAC and access policies?
RBAC provides centralized role-based authorization, while access policies are the Key Vault-specific permission model.
7. What is Soft Delete?
It allows deleted vaults and objects to be recovered during a retention period.
8. What is Purge Protection?
It prevents permanently deleting soft-deleted vaults and objects before the retention period expires.
9. What is a Key Vault secret version?
Each update to a secret creates a new version, allowing version tracking and controlled retrieval.
10. Why should we cache Key Vault secrets?
Caching reduces network calls, latency, and the risk of throttling.
Advanced Questions
11. How do you integrate Azure Key Vault with ASP.NET Core?
Use the Azure Key Vault configuration provider or Azure SDK with SecretClient, authenticated through Managed Identity or DefaultAzureCredential.
12. How do you prevent unauthorized access to Key Vault?
Use Managed Identity, Azure RBAC, least-privilege access, Private Endpoints, firewall restrictions, monitoring, and appropriate identity controls.
13. How do you rotate secrets without downtime?
Use overlapping credentials when supported, update Key Vault, refresh application configuration, verify new connections, and revoke old credentials only after successful migration.
14. What happens if Key Vault is unavailable?
Secret retrieval requests can fail. Applications should implement sensible retry, timeout, caching, and failure-handling strategies.
15. What is the difference between Key Vault and Managed HSM?
Key Vault offers secrets, keys, and certificates. Managed HSM is a specialized service for dedicated hardware-security-module-backed cryptographic key management.
16. What is the difference between control plane and data plane?
- Control plane: Manages the Key Vault resource itself.
- Data plane: Performs operations on stored secrets, keys, and certificates.
17. How do you integrate Key Vault with Azure Kubernetes Service?
Use the Secrets Store CSI Driver with the Azure Key Vault provider and an appropriate workload identity configuration.
18. How do you monitor Key Vault access?
Use diagnostic settings, Azure Monitor, Log Analytics, alerts, and Event Grid.
19. Why should we avoid retrieving secrets on every API request?
It increases latency and service calls and can cause throttling.
20. Can Key Vault automatically update an application's configuration when a secret changes?
Not automatically in every integration. A refresh mechanism must be configured, or the application must explicitly retrieve the updated secret.
18. Official Microsoft Documentation
- Azure Key Vault - Getting Started
- Secure Your Azure Key Vault
- Azure Key Vault Developer's Guide
- Azure Key Vault .NET SDK
- Azure Key Vault RBAC Guide
- Key Vault Soft Delete and Purge Protection
19. Recommended Learning and Implementation Order
- Understand the fundamentals: Secrets vs Keys vs Certificates, authentication, authorization and RBAC.
- Create a Key Vault: Create a vault, configure RBAC, and add sample secrets.
- Implement ASP.NET Core integration: Install NuGet packages and configure AddAzureKeyVault().
- Implement Managed Identity: Connect Azure App Service to Key Vault without application credentials.
- Integrate Entity Framework Core: Retrieve database configuration securely and connect to Azure SQL.
- Implement security: Private Endpoint, least privilege, Soft Delete, Purge Protection and logging.
- Implement performance optimization: Memory caching, retries, client reuse and secret refresh.
- Implement enterprise features: Secret rotation, certificate lifecycle management, Event Grid and Azure DevOps integration.
Conclusion
Pay particular attention to Managed Identity, RBAC, secret rotation, caching, and Private Endpoints. These concepts are especially important when designing secure ASP.NET Core microservices and enterprise applications.
Azure Key Vault protects your secrets, Managed Identity establishes your application's identity, and Azure RBAC determines what your application is allowed to access.
| Azure-Cognitive-Services :👈 | 👉:Azure-SQL |