Almost every serious incident in cloud applications starts the same way: someone found a credential. A connection string in appsettings.Production.json, a client secret pasted into the pipeline, a Storage key that was never rotated. For C# applications on Azure, the good news is that you can eliminate most of those secrets, store the few that remain properly, and surround everything with least-privilege permissions.
This article is the practical walkthrough of that protection, in layers: Managed Identity so there is no password, Azure Key Vault for what still has to be a secret, and tight IAM (Azure RBAC) around both. If the idea of a secrets vault is new to you, start with our article on what a Secrets Manager is; here we go straight to configuration and code.
Summary for those in a hurry
- The best secret is the one that does not exist. Azure SQL, Storage, Service Bus and Key Vault itself accept sign-in by Managed Identity. With no password in the connection string, there is nothing to leak.
- Key Vault is for what is left: third-party API keys, the SMTP password, certificates. One vault per application and per environment.
- In production, an explicit credential: use
ManagedIdentityCredential.DefaultAzureCredentialis great on a developer machine, but in production it can fall back to another credential without telling you. - Minimal IAM: the application gets only Key Vault Secrets User, only on its own vault. No Contributor or Owner for application identities, and no role at subscription level.
- Close the old doors: turn off password authentication in SQL, the shared key in Storage and local authentication in Service Bus. As long as the key exists, it can leak.
- Protect the vault: RBAC instead of access policies, purge protection, restricted network, audit logs and alerts.
- A pipeline with no secret: the GitHub Actions or Azure DevOps deployment signs in to Azure through federation (OIDC), with no stored client secret.
The credential ladder: from worst to best
Every credential in your application sits on one of these rungs. The goal is to move each one as high as possible:
| Rung | Where the secret lives | Problem |
|---|---|---|
1. Code or appsettings.json | In the repository and in Git history | Anyone with access to the code has the production password, forever |
| 2. App Settings or environment variable | In the App Service configuration | Out of Git, but visible to anyone with Contributor on the resource, with no read log and no rotation |
| 3. Key Vault | In the vault, read by identity | The secret still exists and needs rotation, but it has an owner, permissions and an audit trail |
| 4. Managed Identity, no secret | Nowhere | Nothing to leak: Azure issues short-lived tokens to the application |
The rule of thumb: rung 4 whenever the target service accepts Microsoft Entra ID, rung 3 for everything else, and rungs 1 and 2 only for configuration that is not sensitive.
Layer 1: Managed Identity, the application's identity
A Managed Identity is an identity in Microsoft Entra ID created and managed by Azure itself for a resource: App Service, Azure Functions, Container Apps, AKS, a virtual machine. The application asks an internal platform endpoint for a token and uses that token to talk to other services. There is no password, client secret or certificate for you to store, rotate or leak. (To understand Entra ID and the protocols behind it, see our article on identity providers.)
There are two types:
| System-assigned | User-assigned | |
|---|---|---|
| Lifecycle | Created and deleted together with the resource | A standalone resource that you create and delete |
| Sharing | One per resource | The same identity can be used by several resources |
| When to use | One application, one resource, permissions of its own | Several instances or slots with the same permissions, or when the permission must exist before the deployment |
To turn the identity on in an App Service:
az webapp identity assign --resource-group rg-cpw-prod --name cpw-api-prod
One caution with user-assigned identities: since they can be attached to several resources, every resource that uses one inherits all of its permissions. Do not create a single “company” identity for every application. One identity per application and per environment keeps the damage of a compromise small.
Layer 2: the right credential in C# code
The Azure.Identity library delivers everything through a TokenCredential. The best known is DefaultAzureCredential, which tries a list of credentials in sequence: environment variables, Workload Identity, Managed Identity, Visual Studio, Azure CLI and others. It is convenient, because the same code works on the developer machine and in Azure.
In production, however, Microsoft itself recommends replacing it with a specific credential. The reasons:
- Silent fallback to another credential. If Managed Identity fails for a moment, the chain moves on to the next option. If forgotten
AZURE_CLIENT_IDandAZURE_CLIENT_SECRETvariables exist in the environment, the application starts running with another identity and other permissions, with no error at all. - Hard diagnosis. When nothing works, the error lists the failure of every credential in the chain, not the one you expected.
- Slower startup. Each failed attempt costs time before the first request.
The pattern we recommend is to choose the credential by environment, create a single instance and reuse it in every client:
// dotnet add package Azure.Identity
// dotnet add package Microsoft.Extensions.Azure
// dotnet add package Azure.Security.KeyVault.Secrets
// dotnet add package Azure.Storage.Blobs
using Azure.Core;
using Azure.Identity;
using Microsoft.Extensions.Azure;
var builder = WebApplication.CreateBuilder(args);
// Production: Managed Identity only. If it fails, the app fails, and you find out.
// Development: the developer's own sign-in (Visual Studio or "az login").
TokenCredential credential = builder.Environment.IsDevelopment()
? new ChainedTokenCredential(new VisualStudioCredential(), new AzureCliCredential())
: new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);
// user-assigned: ManagedIdentityId.FromUserAssignedClientId("<client-id>")
builder.Services.AddAzureClients(clients =>
{
clients.UseCredential(credential);
clients.AddSecretClient(new Uri(builder.Configuration["KeyVault:Uri"]!));
clients.AddBlobServiceClient(new Uri(builder.Configuration["Storage:BlobUri"]!));
});
Notice what is not in the code or in the configuration: any key. appsettings.json holds only addresses (https://cpw-api-prod.vault.azure.net/), which are not secrets.
If you prefer to keep DefaultAzureCredential, narrow the chain with the AZURE_TOKEN_CREDENTIALS environment variable: the value prod removes developer tool credentials, and ManagedIdentityCredential leaves only the managed identity (with automatic retries from Azure.Identity 1.16 onwards).
Layer 3: passwordless connections (SQL, Storage, Service Bus)
With the identity turned on, the next step is to take the password out of the connections. The main Azure data services accept the Entra ID token in place of a key.
Azure SQL
The connection string no longer has a user and password:
Server=tcp:cpw-sql-prod.database.windows.net,1433;Database=store;
Authentication=Active Directory Managed Identity;Encrypt=True;
Microsoft.Data.SqlClient fetches the token on its own, and Entity Framework Core works with no changes. On the developer machine, use Authentication=Active Directory Default, which reuses the Visual Studio or az login sign-in. In the database, create a user for the identity and grant only what it needs:
CREATE USER [cpw-api-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [cpw-api-prod];
ALTER ROLE db_datawriter ADD MEMBER [cpw-api-prod];
-- no db_owner: the application does not need to change the schema.
-- migrations run in the pipeline, with a different identity.
Storage, Service Bus and the rest
The Azure SDKs follow the same pattern: instead of a connection string with a key, the client receives the resource address and the credential. Permission comes from a data role assigned to the identity:
| Service | Common minimal role | How to turn the key off |
|---|---|---|
| Blob Storage | Storage Blob Data Reader or Contributor | Disable “Allow storage account key access” |
| Service Bus | Azure Service Bus Data Sender / Data Receiver | Disable local (SAS) authentication |
| Azure SQL | Database user with db_datareader / db_datawriter | Enable “Microsoft Entra-only authentication” |
| Cosmos DB | Cosmos's own data role (Built-in Data Contributor) | Disable key authentication (disableLocalAuth) |
The third column is the one most often forgotten. Migrating the application to Managed Identity and leaving the old key enabled does not reduce the risk: the key is still valid, with full access, somewhere. After confirming that nothing else uses the key, turn that kind of authentication off on the resource.
Layer 4: Key Vault for what is still a secret
Something is always left: the payment gateway key, the WhatsApp API token, the SMTP password, a certificate. That goes into Azure Key Vault. In C# there are two ways to consume it, and they can coexist.
Option A: Key Vault references in App Service
You create an App Setting whose value is a reference to the secret, and the platform resolves it before handing it to the application:
# App Setting "Payments__ApiKey"
@Microsoft.KeyVault(SecretUri=https://cpw-api-prod.vault.azure.net/secrets/payments-api-key/)
The code reads Configuration["Payments:ApiKey"] like any other setting, with no extra package and not a single line about Key Vault. If the reference does not pin a version, App Service starts using the newest version of the secret within 24 hours. It works in App Service and Azure Functions; Container Apps has an equivalent feature.
Option B: the .NET configuration provider
// dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
using Azure.Extensions.AspNetCore.Configuration.Secrets;
builder.Configuration.AddAzureKeyVault(
new Uri(builder.Configuration["KeyVault:Uri"]!),
credential,
new AzureKeyVaultConfigurationOptions
{
// re-read the secrets periodically, to keep up with rotation
ReloadInterval = TimeSpan.FromMinutes(30)
});
// the secret "Payments--ApiKey" in the vault becomes "Payments:ApiKey" in configuration
Here the application loads every secret in the vault at startup and keeps them in memory. For rotation to reach the code without a restart, read the values through IOptionsMonitor<T> or IOptionsSnapshot<T>, not from a value copied into a static field at startup.
| Key Vault reference | Configuration provider | |
|---|---|---|
| Code change | None | A package and a few lines in Program.cs |
| Where it works | App Service and Functions | Anywhere .NET runs (AKS, Container Apps, VM) |
| Update on rotation | Within 24 hours, or on restart | At the interval you define |
| What the application sees | Only the referenced secrets | Every secret in the vault |
In either case, do not call the vault on every request. Key Vault has a call limit (about 4,000 secret operations every 10 seconds per vault) and answers with a 429 error when the limit is exceeded. Read secrets at startup and keep them in memory.
Layer 5: IAM, who can do what
This is where most setups fail. Having a vault does not help if half the company can read what is inside it.
RBAC, not access policies
Key Vault has two permission models. The old one, access policies, has a known flaw: anyone with the Contributor role on the vault can change the policies and grant themselves access to the secrets. The Azure RBAC model separates who manages the resource from who reads the data, allows per-secret scope and works with Privileged Identity Management (PIM). As we showed in the Secrets Manager article, vaults created with API version 2026-02-01 or later already default to RBAC, and the older API versions will be retired on February 27, 2027. If your vault still uses access policies, plan the migration.
The roles that matter
| Role | What it allows | For whom |
|---|---|---|
| Key Vault Secrets User | Read secret values | The application's identity |
| Key Vault Secrets Officer | Create, change and delete secrets | The rotation automation and the person responsible for the secrets |
| Key Vault Reader | See names and metadata, without reading values | Monitoring and auditing |
| Key Vault Crypto User | Use keys to encrypt, decrypt and sign | Applications that use keys, not secrets |
| Key Vault Certificate User | Read certificates | Applications and gateways that load TLS |
| Key Vault Administrator | Everything in the data plane | Very few people, and preferably only on demand |
The assignment for the application looks like this, scoped to the vault, not to the resource group or the subscription:
az role assignment create \
--role "Key Vault Secrets User" \
--assignee-object-id $(az webapp identity show -g rg-cpw-prod -n cpw-api-prod --query principalId -o tsv) \
--assignee-principal-type ServicePrincipal \
--scope $(az keyvault show -n cpw-api-prod --query id -o tsv)
Rules to get it right
- One vault per application and per environment. This is Microsoft's recommendation. That way the role on the vault already is least privilege: the orders API does not read the billing key, and staging reads nothing from production.
- An application identity never gets Owner or Contributor. Those roles belong to the management plane. An application that only reads secrets and writes blobs needs two data roles, and nothing else.
- Scope at the resource. A data role assigned at the subscription applies to every vault and every Storage account, today's and tomorrow's.
- Assign the role directly to the identity, not to a group. Managed Identity tokens are cached for up to 24 hours. Removing the identity from a group can take hours to take effect; removing a direct role assignment takes minutes.
- People have no standing access to production. Developers read the development vault. For production, use PIM: access is requested, justified, approved, lasts a few hours and is logged.
- Whoever administers is not whoever reads. With RBAC, someone with Contributor on the vault manages network and configuration without seeing the secrets. Only Owner and User Access Administrator can assign roles, so watch who holds those two.
- Review regularly. Assignments for people who left the team, for retired applications and for “temporary” tests pile up. A quarterly review (Entra ID access reviews help) cleans that up.
Layer 6: protecting the vault itself
- Soft delete and purge protection. Soft delete is already mandatory and keeps deleted vaults and secrets for up to 90 days. Turn on purge protection too: with it, not even an administrator (or an attacker with their account) can permanently delete before the retention period ends. Without it, deleting and purging the vault is a quick way to take the whole application down.
- Restricted network. By default, the vault answers on the public internet to anyone with a valid token. In production, use a private endpoint and disable public access, or at least limit the vault firewall to the application's networks and subnets. That way a stolen token does not work from outside.
- Audit logs. Enable diagnostic settings and send the
AuditEventcategory to a Log Analytics workspace. Every secret read is recorded with identity, IP and result. - Alerts. Microsoft Defender for Key Vault warns about unusual access, such as bulk reads or access from a suspicious IP. At the very least, create an alert for 403 responses, which mean someone is trying to read what they are not allowed to:
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.KEYVAULT" and httpStatusCode_d == 403
| summarize attempts = count() by CallerIPAddress, OperationName, bin(TimeGenerated, 1h)
- Expiry and rotation. Set an expiration date on every secret. Key Vault publishes events to Event Grid when a secret is close to expiring, and an Azure Function can do the swap. Whatever cannot be automated needs a date and an owner.
- Azure Policy. There are built-in policies that require RBAC, purge protection, private access and an expiration date on every vault in the subscription. That way the next vault created in a hurry is born compliant.
Layer 7: the pipeline and the developer machine
Deploying without a client secret
It is common for the application to be flawless while the pipeline stores a client secret with Contributor on the whole subscription, valid for two years. That secret is, in practice, the key to the entire infrastructure. The fix is identity federation (OIDC): GitHub Actions or Azure DevOps presents a signed token, and Entra ID exchanges it for an access token, with no stored secret.
permissions:
id-token: write # lets the job request the OIDC token
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
The three values are identifiers, not secrets. In the federated credential, restrict the subject to the repository and the environment (repo:your-org/your-api:environment:production), so that only the approved production deployment can get the token. And give the pipeline identity a role only on the application's resource group.
Local development
- The developer's identity: with
az loginor the Visual Studio sign-in, the same code reaches the development vault and database with the person's own account. Nobody needs a copy of a secret on their machine. - User Secrets: for truly local values, use
dotnet user-secrets set "Payments:ApiKey" "...". The file lives outside the project folder, so it does not go to Git. Be aware that it is not encrypted, so it should only hold test credentials. - Never production. Debugging locally against the production database is the shortcut that ends in an incident. If it is unavoidable, do it with temporary access through PIM.
Bonus: ASP.NET Core's own keys
There is one secret many people forget: the Data Protection keys, which ASP.NET Core uses to encrypt authentication cookies and antiforgery tokens. With more than one instance they have to be shared, and the right place is a blob protected by a Key Vault key:
// dotnet add package Azure.Extensions.AspNetCore.DataProtection.Blobs
// dotnet add package Azure.Extensions.AspNetCore.DataProtection.Keys
builder.Services.AddDataProtection()
.PersistKeysToAzureBlobStorage(
new Uri("https://cpwprod.blob.core.windows.net/dataprotection/keys.xml"), credential)
.ProtectKeysWithAzureKeyVault(
new Uri("https://cpw-api-prod.vault.azure.net/keys/dataprotection"), credential);
The application's identity needs the Key Vault Crypto User role on the vault and a blob data role on the container. Anyone able to read those keys unprotected can forge valid sign-in cookies.
Common mistakes
- Keeping the key to the vault outside the vault. Using
ClientSecretCredentialwith the client secret inappsettings.jsononly moves the secret somewhere else. Inside Azure, use Managed Identity; outside it, identity federation. - Migrating and not turning the key off. The application uses Managed Identity, but the old connection string is still valid in a backup, on a laptop or in another system.
- Contributor on the subscription “to make it work”. It fixes the 403 error on the spot and creates a much bigger problem. A 403 is almost always a missing data role on the right resource.
- A single vault for every environment. With the role at vault level, staging gets to read production secrets.
- Printing the configuration to the log. A
logger.LogInformation("{Config}", config)at startup sends the secrets to Application Insights, where far more people have access. - Secrets with no expiration date. With no date nobody is warned, and the 2022 key is still valid.
- A secret that has been in Git. Moving it to the vault does not erase the history. Treat it as leaked and change the value.
- A vault open to the internet in production. It works, but leaves security depending on the token alone. A restricted network is the second barrier.
Checklist
- Managed Identity turned on for each application, one identity per application and per environment
ManagedIdentityCredential(or a narrowed chain) in production, a single reused instance- SQL, Storage and Service Bus accessed by identity, with no password in the connection string
- Key authentication turned off on resources already migrated
- One Key Vault per application and per environment, with Azure RBAC
- Application with Key Vault Secrets User, scoped to its own vault
- No application identity with Owner or Contributor; no data role at the subscription
- People access production only on demand (PIM), with MFA
- Purge protection enabled and the vault network restricted
AuditEventlogs in Log Analytics, with an alert for 403 and Defender for Key Vault- Secrets with an expiration date and a defined rotation
- Pipeline with OIDC federation, no client secret, and a role limited to the resource group
- Data Protection keys in a blob, protected by a Key Vault key
- Secret scanning enabled on the repository (GitHub Secret Scanning or Gitleaks)
Sources
- Microsoft Learn: authentication best practices with the Azure Identity library for .NET
- Microsoft Learn: credential chains in the Azure Identity library for .NET
- Microsoft Learn: managed identity best practice recommendations
- Microsoft Learn: secure your Azure Key Vault
- Microsoft Learn: Key Vault access with Azure RBAC
- Microsoft Learn: Key Vault references in App Service and Azure Functions
- Microsoft Learn: Key Vault configuration provider in ASP.NET Core
- Microsoft Learn: migrate to passwordless connections with Azure SQL
- Microsoft Learn: Key Vault service limits
- Microsoft Learn: GitHub Actions to Azure with OpenID Connect
- Microsoft Learn: configure ASP.NET Core Data Protection
- OWASP: Secrets Management Cheat Sheet
Need help?
Want to take the passwords out of your .NET application, migrate to Managed Identity and Key Vault, or review the permissions in your Azure environment? Talk to us: we run the credentials and IAM assessment and do the migration environment by environment, without taking the system down.


