Pipeline secret management for .NET on Azure: OIDC and workload identity federation instead of stored credentials, managed identity at run time, Key Vault references, least-privilege identities, secret scanning and leak response.
My rule is to remove secrets rather than protect them. The pipeline authenticates to Azure with OIDC / workload identity federation: the CI platform issues a short-lived token that Entra trusts, so no client secret is stored. The app authenticates to SQL, Storage and Key Vault with managed identity. Remaining secrets (third-party API keys) live in Key Vault; the pipeline deploys only a Key Vault reference such as @Microsoft.KeyVault(VaultName=...;SecretName=...) as an app setting, and the platform resolves it with the app's identity, so the value never passes through the pipeline.
Pipeline identities are least privilege: one per environment, roles on a resource group, protected by environment approvals. Secret scanning with push protection blocks committed secrets.
If a secret leaks, I revoke and rotate first, then clean logs, then check access logs. The trade-off is up-front identity setup in exchange for nothing worth stealing in the pipeline.
"I start by shrinking the problem. Most secrets in pipelines exist only because something can't use identity. So the pipeline itself logs in to Azure through OIDC: GitHub or Azure DevOps issues a short-lived token, Entra trusts it through a federated credential, and there's nothing stored to leak or rotate. The application uses managed identity for Azure SQL, Storage, Service Bus and Key Vault, so there are no connection-string passwords either. For the few real secrets left, like a payment provider API key, I put them in Key Vault and let the app fetch them at run time: an App Service or Container Apps Key Vault reference, or the Key Vault configuration provider. The pipeline deploys a reference, never the value.
Then least privilege. Each environment has its own pipeline identity with roles only on its resource group; the production one can only be used by a job targeting the protected production environment, which needs an approval and only runs from
main. For example, at [company] we [found a service connection with Owner on the subscription used by 30 pipelines, replaced it with per-environment federated identities, and cut the number of identities with production write access from 30 to 4].The mistake I see is relying on log masking. Masking only hides exact matches; if a script base64-encodes a secret, prints part of it, or a tool echoes it in a URL, it's in the log. And when a secret does leak, people delete the log and move on. The secret is compromised the moment it's printed, so the first move is always revoke and rotate, then clean up and investigate what it could access."
| Preference | Mechanism | Example |
|---|---|---|
| 1. No secret at all | OIDC / workload identity federation; managed identity | Pipeline → Azure; app → Azure SQL with Authentication=Active Directory Default |
| 2. Secret only the app reads | Key Vault + managed identity at run time | @Microsoft.KeyVault(SecretUri=...) app setting |
| 3. Secret the pipeline must use | Key Vault-linked variable group / fetch with azure/get-keyvault-secrets or az keyvault secret show at the step that needs it |
Signing certificate password for a NuGet package |
| 4. Last resort | Platform secret store (GitHub environment secret, Azure DevOps secret variable) | Token for a tool without identity support |
| Do | Don't |
|---|---|
| One identity per environment | One identity for dev, test and prod |
| Roles on a resource group or resource | Owner/Contributor on the subscription |
User Access Administrator only when deploying role assignments, ideally with conditions limiting assignable roles |
Broad role-assignment rights |
Federated credential bound to environment:production |
Trust bound to any branch or PRs |
| Approvals and branch control on the prod environment/service connection | Anyone with repo write can deploy prod |
After moving 40 pipelines from stored service principal secrets to federated identities and Key Vault references, a team removed 55 stored secrets, ended a quarterly rotation that took about two days of effort, and passed an Essential Eight assessment item on restricting administrative privileges that had previously been flagged.
Checks whether the candidate designs pipelines with identity instead of secrets, applies least privilege per environment, and knows how to respond to a leak.
Green flags
Red flags
┌────────────── build ──────────────┐ ┌────── deploy (prod) ───────┐
repo ───► │ OIDC → id-build (AcrPush on ACR) │ ──► │ OIDC → id-deploy-prod │
└──────────────────────────────────────┘ │ (Contributor on rg-orders-prod) │
└──────────────┬────────────────┘
│ deploys app + reference
▼
app's managed identity ──► Key Vault (Key Vault Secrets User)
──► Azure SQL (db user from external provider)
──► ACR (AcrPull)
The pipeline's job is to put the right code and configuration in place; the app's identity reads the secrets. The deploy identity doesn't need Key Vault Secrets User at all.
permissions: id-token: write, azure/login with client-id, tenant-id, subscription-id. The federated credential subject (repo:org/repo:environment:production) decides which jobs qualify.App Service, Functions and Container Apps can resolve a secret from Key Vault using the app's managed identity:
@Microsoft.KeyVault(SecretUri=https://kv-orders-prod.vault.azure.net/secrets/PaymentApiKey/). Without a version, the platform picks up new versions (refreshed periodically, within about 24 hours, or immediately on a config change/restart).keyVaultUrl and an identity, then referenced by an environment variable secretRef.builder.Configuration.AddAzureKeyVault(uri, new DefaultAzureCredential()) with a ReloadInterval if you need faster rotation.Use RBAC on Key Vault (not legacy access policies), enable soft delete and purge protection, and private endpoints for production vaults.
Platforms mask the exact string of a registered secret in logs. They don't mask:
ARG/ENV in a Dockerfile).So design so secrets never reach steps that might print them, and keep set -x / verbose logging off around them.
dotnet user-secrets locally keeps development secrets out of the repo.ACSC Essential Eight's "restrict administrative privileges" maps directly onto per-environment, least-privilege pipeline identities with approvals. If a leaked credential could expose personal information, the organisation must assess whether it's an eligible data breach under the NDB scheme (assessment within 30 days, notify OAIC and affected individuals if likely to cause serious harm).
az role assignment list --assignee <id> --all and remove anything broader than a resource group.The app reads its own secrets with managed identity, so the pipeline never sees them, and it fails fast and visibly if Key Vault can't be reached (Program.cs):
using Azure;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
if (!builder.Environment.IsDevelopment())
{
try
{
// Managed identity in Azure; no client secret anywhere.
builder.Configuration.AddAzureKeyVault(
new Uri(builder.Configuration["KeyVault:Uri"]!),
new DefaultAzureCredential(),
new AzureKeyVaultConfigurationOptions
{
// Re-reads the latest secret versions, so a rotation needs no redeploy.
ReloadInterval = TimeSpan.FromMinutes(15)
});
}
catch (Exception ex) when (ex is RequestFailedException or AuthenticationFailedException)
{
// 403 = missing RBAC role or firewall; auth failure = identity not assigned.
// Log without the secret, then stop: running without secrets is worse than not starting.
Console.Error.WriteLine($"Key Vault load failed: {ex.GetType().Name} {(ex as RequestFailedException)?.Status}");
throw;
}
}
// In development the same keys come from `dotnet user-secrets`.
builder.Services.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection("Payment")) // Key Vault secret name: Payment--ApiKey
.Validate(o => !string.IsNullOrWhiteSpace(o.ApiKey), "Payment:ApiKey is missing")
.ValidateOnStart(); // also catches an unresolved Key Vault reference
var app = builder.Build();
app.MapGet("/health/live", () => Results.Ok());
app.Run();
public sealed class PaymentOptions
{
public string ApiKey { get; set; } = "";
}
If an App Service Key Vault reference can't be resolved, the setting contains the literal @Microsoft.KeyVault(...) text, so ValidateOnStart with a format check (for example !o.ApiKey.StartsWith("@Microsoft.KeyVault")) turns a silent misconfiguration into a failed deployment that the slot swap's warm-up will catch.
The deploy step passes a reference, not the value, and the identity is federated:
deploy-prod:
environment: production # approval + main-only
runs-on: ubuntu-latest
permissions: { id-token: write, contents: read }
steps:
- uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_CLIENT_ID_PROD }} # identifier, not a secret
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- name: Point the app at Key Vault (value never enters the pipeline)
run: |
az webapp config appsettings set -g rg-orders-prod-aue -n app-orders-prod-aue --slot staging --settings \
"[email protected](VaultName=kv-orders-prod-aue;SecretName=PaymentApiKey)"
# Least privilege: the app reads secrets; the pipeline identity gets no Key Vault data role
az role assignment create --assignee <app-managed-identity-principal-id> \
--role "Key Vault Secrets User" \
--scope /subscriptions/<sub>/resourceGroups/rg-orders-prod-aue/providers/Microsoft.KeyVault/vaults/kv-orders-prod-aue
# Regular audit: who can read secrets in this vault?
az role assignment list --scope <vault-resource-id> --query "[].{who:principalName, role:roleDefinitionName}" -o table
ARG or ENV. Why it is wrong: They're stored in image layers and history. Instead: Use BuildKit secret mounts at build time and runtime identity for the app.get/list for many principals. Why it is wrong: Hard to audit, not least privilege. Instead: Use Azure RBAC on the vault with narrow roles.The senior move is to treat secret management as identity design. Every stored secret is a liability with a rotation cost and a leak risk, so I count them and drive the number towards zero: federated identity for pipelines, managed identity for apps, Key Vault for the remainder, read only by the workload that needs it.
The controls belong on the identity and the environment, not in pipeline YAML that any contributor can edit. And it isn't a one-off project: I schedule a quarterly review of role assignments on vaults and resource groups (Entra access reviews or a script over az role assignment list), alert on Key Vault access from unexpected identities in Log Analytics, use Azure Policy to deny shared-key storage access and Key Vaults without purge protection, and track three numbers over time: stored secrets, identities with production write access, and time to rotate a credential end to end.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| OIDC / workload identity federation | Pipeline → Azure (and AWS, GCP) | One-off identity setup | Never worse than a stored secret |
| Managed identity at run time | App → Azure services | Role assignments per resource | Services without Entra auth |
| Key Vault reference | Third-party keys the app needs | Vault, RBAC, rotation process | Values the pipeline truly needs (e.g. signing) |
| Platform secret store | Tools with no identity option | Manual rotation, leak risk | Anything that supports identity |
The workflow has a build job (restore, build, test, dotnet publish /t:PublishContainer to push an image tagged with the commit SHA to Azure Container Registry) and deploy jobs per environment that reuse that same image.
For Azure access I use OpenID Connect: the job declares permissions: id-token: write, GitHub issues a short-lived token, and azure/login exchanges it for an Entra token through a federated credential on an app registration or user-assigned managed identity. No client secret is stored anywhere.
Production is gated with a GitHub environment that has required reviewers, and the federated credential's subject is scoped to environment:production, so only an approved job can get production access.
The trade-off: OIDC needs one-off Entra setup per repo and environment, but removes secret rotation and leaked-secret risk entirely.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
Database.Migrate() at start-up means the runtime identity must hold DDL rights, so any SQL injection or RCE can alter or drop schema. It also couples deployment to start-up: several scaled-out instances can try to migrate at once (EF Core 9+ takes a database lock to serialise this, but a long migration still blocks start-up and health checks), and a failed migration takes the app down with it. Instead I generate an idempotent script or a migration bundle (dotnet ef migrations bundle) in CI and run it once in the release stage under a separate migration identity with db_ddladmin, after a backup and an approval gate for production. Migrations are written to be backward compatible (expand, then contract) so the old and new app versions both work during rollout, and the runtime identity keeps only DML.
How to tell it (STAR)
**S:** A storage key for a service holding sensitive customer documents ended up readable in a pipeline log. **T:** I owned the response and needed to contain it and make sure it couldn't happen again. **A:** I rotated the key first, then deleted the logs, checked Storage diagnostics in Log Analytics for any use of the old key, and gave the privacy officer the evidence for the breach assessment; then I replaced key-based access with managed identity and a federated pipeline identity and turned shared key access off by policy. **R:** The key was rotated within [about 15 minutes], logs showed [no unauthorised access], and the account has had [no stored keys] since.
Last updated 23 Nov 2026.