Azure Key Vault and Managed Identity for .NET
On this page
Learning Objective
Configure the production application with settings and Key Vault references instead of embedded secrets, grant access with managed identity and least-privilege role assignments, connect to Azure SQL without a password, set up rotation and vault protections, and audit access to secrets.
Concept Explanation
Day 49 introduced managed identities and Key Vault as concepts. Production configuration turns them into a repeatable setup. The principle is that the deployed application should contain no secrets and hold no long-lived credentials. Everything it needs to authenticate to other Azure services comes from its identity, and the few real secrets it needs, such as a third-party API key, live in Key Vault, referenced by the platform. A developer who has read access to the repository and the deployed configuration should still not be able to obtain any secret, and a leak of the application's environment variables should not reveal anything usable.
App Service and Container Apps support Key Vault references in application settings. Instead of putting the value of a secret into a setting, you set the setting to a reference such as the Key Vault secret URI, and the platform resolves it at runtime using the app's managed identity and injects the value as an environment variable. The application reads it like any other configuration, so no code changes are needed, and rotating the secret in Key Vault takes effect without redeploying. Settings that identify a deployment slot, such as the environment name or a connection to a staging database, should be marked slot-specific so a slot swap does not carry them to production.
Access is controlled with Azure role-based access control at the smallest scope that works. The application's identity gets Key Vault Secrets User on the specific vault to read secrets, Storage Blob Data Contributor on the specific container, and Azure Service Bus Data Sender or Receiver on specific queues. Azure SQL supports Microsoft Entra authentication, so the application connects with a token instead of a password: you create a contained database user for the identity and grant it the roles of Day 34, and the connection string simply states the authentication method. There is no password to store, rotate, or leak, and access can be revoked by removing the user. Local development uses your own developer identity through the Azure CLI or Visual Studio sign-in, so the same code path works everywhere.
Protect the vault itself. Enable soft delete and purge protection so an attacker or accident cannot permanently destroy keys and secrets quickly; Azure now enforces soft delete on all vaults. Restrict network access with a private endpoint or the vault firewall, and turn on diagnostic logging to a Log Analytics workspace so that every read of a secret is recorded and unusual access can trigger alerts. Prefer separate vaults per environment and per sensitivity so that a staging identity can never read production secrets. Plan rotation: secrets that must exist should have expiry dates, with Event Grid notifications as they near expiry, and applications should tolerate a changed value. When a secret is suspected leaked, rotate it at the source first, update Key Vault, and verify the old value no longer works.
| Need | Mechanism | Result |
|---|---|---|
| Third-party secret at runtime | Key Vault reference in app settings | Platform injects it, no secret in configuration |
| Access to Azure services | Managed identity plus RBAC role | No credentials, revocable, auditable |
| Database access | Entra authentication with a contained user | Passwordless SQL connection |
| Slot swaps | Slot-specific settings | Staging values never move to production |
| Vault protection | Soft delete, purge protection, private endpoint | Resists deletion and network attack |
| Detection | Diagnostic logs and alerts on secret access | Unusual reads are noticed |
Worked Example: Key Vault References, RBAC, a Passwordless SQL User and Vault Protections
The commands grant the identity only the roles it needs, set Key Vault references and a passwordless connection string, create the SQL user, and protect and monitor the vault.
RG=rg-taskboard-prod; APP=taskboard-web; KV=kv-taskboard-prod; SQLSRV=sql-taskboard; DB=TaskBoard
PRINCIPAL_ID=$(az webapp identity show -g $RG -n $APP --query principalId -o tsv)
# 1. Least-privilege roles, scoped to individual resources rather than the whole subscription.
KV_ID=$(az keyvault show -n $KV --query id -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
--role "Key Vault Secrets User" --scope $KV_ID # read secrets, cannot write or delete
STORAGE_ID=$(az storage account show -n sttaskboardprod --query id -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
--role "Storage Blob Data Contributor" --scope "$STORAGE_ID/blobServices/default/containers/attachments"
# 2. Settings: values are references, not secrets. The platform resolves them with the app's identity.
az webapp config appsettings set -g $RG -n $APP --settings \
"Entra__ClientSecret=@Microsoft.KeyVault(SecretUri=https://$KV.vault.azure.net/secrets/entra-client-secret/)" \
"Payments__ApiKey=@Microsoft.KeyVault(SecretUri=https://$KV.vault.azure.net/secrets/payments-api-key/)" \
"ConnectionStrings__Default=Server=tcp:$SQLSRV.database.windows.net,1433;Database=$DB;Authentication=Active Directory Default;Encrypt=True;TrustServerCertificate=False"
# 3. Slot-specific: these must not travel with a slot swap.
az webapp config appsettings set -g $RG -n $APP --slot-settings ASPNETCORE_ENVIRONMENT=Production
# 4. Vault protections and audit trail.
az keyvault update -n $KV --enable-purge-protection true --public-network-access Disabled # set --retention-days when the vault is created
az monitor diagnostic-settings create --name kv-audit --resource $KV_ID --workspace $LOG_WORKSPACE_ID \
--logs '[{"category":"AuditEvent","enabled":true}]'-- Passwordless database access: run once as the Entra admin. The user name is the app's resource name.
CREATE USER [taskboard-web] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [taskboard-web];
ALTER ROLE db_datawriter ADD MEMBER [taskboard-web];
-- No db_owner, no ALTER: schema changes run under a separate, pipeline-only identity (Day 34).// The application code is unchanged by all of this: it reads configuration and connects.
builder.Services.AddDbContext<AppDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
// "Authentication=Active Directory Default" uses the managed identity in Azure and your az login locally.
builder.Services.AddOptions<EntraOptions>().Bind(builder.Configuration.GetSection("Entra"))
.ValidateDataAnnotations().ValidateOnStart(); // a missing or unresolved Key Vault reference fails startup loudly# Detection: alert when secrets are read by an unexpected identity or at an unusual rate (KQL over the AuditEvent logs).
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.KEYVAULT" and OperationName == "SecretGet"
| where identity_claim_oid_g !in ("<app-identity-oid>", "<pipeline-identity-oid>")
| project TimeGenerated, CallerIPAddress, identity_claim_oid_g, requestUri_s
# Any result is worth a look: a person or an unknown service read a production secret.# Rotation runbook for a leaked or expiring secret
1. Create a new credential at the provider (payments dashboard, Entra app registration).
2. Add it to Key Vault as a NEW VERSION of the same secret. Key Vault references without a pinned version pick it up.
3. Restart or wait for the platform refresh; verify a successful call with the new credential.
4. Revoke the OLD credential at the provider. Confirm it fails.
5. Search the AuditEvent log for reads of the old version between exposure and revocation.Note that the ValidateOnStart from Day 9 pays off here: an unresolved Key Vault reference, for example because the role assignment is missing, makes the app fail at startup with a clear message, instead of failing later on the first payment.
Real-World Examples
- Microsoft has made soft delete mandatory for Azure Key Vault, so deleted vaults and secrets are retained and recoverable for a configurable period, and recommends purge protection for production vaults so retained items cannot be permanently deleted early. The defaults reflect incidents where destroyed keys caused data loss or where attackers used deletion as part of ransom-style attacks.
- Azure's Instance Metadata Service, which hands managed identity tokens to workloads, requires a Metadata header on requests and blocks requests carrying forwarded headers, specifically to reduce the risk that a server-side request forgery flaw in an application can be used to steal tokens. The mitigation is one reason managed identities are safer than static credentials, though the application must still avoid SSRF as Day 50 described.
Review Questions & Answers
The secret value never appears in the app's configuration, deployment templates, or portal, so anyone with configuration access does not obtain it. The platform resolves it at runtime using the app's identity, and rotating the secret in Key Vault takes effect without changing or redeploying the application.
Least privilege limits what a compromised application can reach. Secrets User allows only reading secrets from that one vault, so an attacker who steals the app's token cannot write or delete secrets, read other vaults, or affect unrelated resources. Broad roles turn one compromised identity into access to everything.
There is no database password to store, leak, or rotate. The application obtains short-lived tokens from Entra ID, and access is controlled by a database user mapped to its identity, which you can remove instantly. Attackers cannot reuse a password from a leaked configuration file because none exists.
Slot swaps exchange the content and settings of two slots, so a setting such as the environment name or a staging database would move into production if it were not pinned to its slot. Slot-specific settings stay with the slot, so swapping a warmed-up staging build into production does not carry environment configuration with it.