📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you manage secrets in a .NET 10 application? What counts as a secret, how do Azure Key Vault and managed identity fit together, and how do developers work locally without any secrets in the repository?

Secrets management fundamentals: what is and isn't a secret, Key Vault with managed identity and DefaultAzureCredential, the configuration provider, user secrets locally, removing secrets entirely with identity-based access, and rotation basics.

Intermediate Theory Intermediate azure-key-vault configuration managed-identity secrets-management security user-secrets

🎯 Key points

  • A secret is anything that grants access or proves identity: passwords, connection strings with credentials, API keys and OAuth tokens, client secrets, JWT signing and encryption keys, SAS tokens, certificate private keys, and sensitive runtime-issued credentials
  • Best secret is no secret: managed identity to Azure SQL, Storage, Service Bus and Key Vault itself
  • Key Vault stores what must remain a secret (typically third-party API keys that don't support Entra); app reads it via AddAzureKeyVault with a managed identity
  • Key Vault and Entra become runtime dependencies: load at start-up, cache, reload on an interval, and know the vault's throttling limits and network path (private endpoint, firewall)
  • DefaultAzureCredential locally; a narrower ManagedIdentityCredential in production
  • Locally: dotnet user-secrets (outside the repo, plaintext) or a developer's own Entra sign-in to a dev Key Vault
  • Never in appsettings.json, launchSettings.json, Dockerfiles, pipeline YAML or logs; GitHub push protection or gitleaks in CI
  • Rotation is automated, not heroic: versioned secrets, two-key overlap for third-party keys, expiry events, per-app vaults with Key Vault Secrets User

⏱ 30-second answer

A secret is anything that grants access or proves identity: database passwords, API keys and tokens, client secrets, JWT signing keys, SAS tokens. The best secret is no secret at all: in Azure I use managed identity so the app authenticates to Azure SQL, Storage and Service Bus with Entra tokens, not stored credentials. What must remain a secret, typically a third-party API key that doesn't support Entra, goes in Azure Key Vault, read through the AddAzureKeyVault configuration provider using the app's managed identity, with Key Vault RBAC per app and a vault per environment. Locally, developers use dotnet user-secrets or their own Entra sign-in against a dev vault. Nothing goes in appsettings.json or the repo, and secret scanning blocks pushes. The trade-off: Entra and Key Vault become runtime dependencies with network hops and throttling limits, so you load at start-up, cache and reload on an interval, and automate rotation rather than doing it by hand.

🗣 Full answer (senior)

How I would answer this in an interview

"I define a secret as anything that grants access or proves identity: passwords, connection strings with credentials, API keys, OAuth client secrets, signing and encryption keys, SAS tokens and certificate private keys. A database server name or a feature flag isn't a secret; it's configuration. That distinction matters because secrets need rotation, access control and audit, while configuration just needs to be correct.

My first move is to get rid of secrets. In Azure, an App Service, Container App or AKS workload gets a managed identity, and it authenticates to Azure SQL, Blob Storage, Service Bus and Key Vault with Entra tokens. The connection string becomes Authentication=Active Directory Default with no password, and there's nothing to leak or rotate. For what's left - a Stripe key, a partner's API key, a webhook signing secret - I put it in Key Vault, one vault per environment, and give each app the Key Vault Secrets User role on its own vault only. The app loads secrets through the AddAzureKeyVault configuration provider, so code still uses IOptions<T> and doesn't know where the value came from.

Locally, developers either use dotnet user-secrets, which stores JSON in their user profile outside the repo, or authenticate with their own Entra account through DefaultAzureCredential to a dev Key Vault. The mistake I see is treating appsettings.Development.json as 'safe enough' and committing a real key; Git history is forever, so I turn on GitHub push protection or gitleaks in CI. The senior point is that secrets management is mostly about reducing the number of secrets, then controlling and rotating the few you can't remove."


Secret or configuration?

Value Secret? Where it goes
SQL password / connection string with password Yes Remove with managed identity; otherwise Key Vault
SQL server and database name No appsettings / App Configuration
Third-party API key (Stripe, SendGrid) Yes Key Vault
OAuth client secret Yes Prefer certificate or federated credential; else Key Vault
JWT signing key / Data Protection key Yes Key Vault keys (non-exportable where possible)
Storage account key Yes Disable shared key; use managed identity + RBAC
Feature flag, log level, timeout No App Configuration / appsettings
Entra tenant id, client id No appsettings (they're identifiers, not credentials)

The options, best first

Option How it works Use when
Managed identity, no secret Platform issues tokens to the workload; resource trusts Entra Target is an Azure service that supports Entra auth
Workload identity federation External workload (GitHub Actions, AKS pod) exchanges its OIDC token for an Entra token CI/CD and Kubernetes
Key Vault + managed identity Secret stored once; app reads it with its identity Third-party credentials you can't remove
Environment variables from the platform App Service settings with Key Vault references Simple apps; still sourced from Key Vault
User secrets JSON in %APPDATA%\Microsoft\UserSecrets or ~/.microsoft/usersecrets Local development only

Production example

Moving [a claims API] to managed identity removed [7 of 9] secrets from its configuration: SQL, Storage, Service Bus, Redis (Entra auth) and the Key Vault access itself. The remaining two partner API keys went into Key Vault with a 5-minute reload interval, so rotation no longer needed a redeploy, and the yearly "rotate everything" exercise dropped from [two days of coordinated deploys] to [an hour].

🔍 What the interviewer is checking

Checks whether the candidate understands secrets as a risk to minimise, not just values to hide, and knows the practical Azure and .NET tooling.

Green flags

  • Distinguishes secrets from configuration.
  • Leads with managed identity to remove secrets.
  • Explains the Key Vault configuration provider, RBAC and per-environment vaults.
  • Knows user secrets are plaintext and dev-only.
  • Mentions secret scanning and rotation.

Red flags

  • "We encrypt the connection string in appsettings."
  • Stores a Key Vault client secret in config.
  • Thinks .gitignore alone is a secrets strategy.

📚 Learn in depth

1. Why secrets are a liability

A secret is a bearer credential: whoever holds it is the app. Every copy is a place it can leak: the repo, a developer laptop, CI logs, a container image layer, a crash dump, a support ticket. The ACSC's guidance and most Notifiable Data Breaches reports trace a large share of incidents back to compromised credentials. So the strategy is ordered: eliminate, then centralise, then control, then rotate.

2. How managed identity removes the secret

  App Service / Container App / AKS pod
        |
        | 1. ask local identity endpoint (IMDS / IDENTITY_ENDPOINT)
        v
  Azure platform  --2. issues Entra access token for audience
        |              https://database.windows.net/ or https://vault.azure.net
        v
  App --3. presents token--> Azure SQL / Key Vault / Storage
                              4. resource validates token, checks RBAC or DB user

There's still a credential, but the platform holds it, rotates it, and it never appears in your configuration. Tokens live about an hour and are cached by Azure.Identity.

3. DefaultAzureCredential and its chain

DefaultAzureCredential tries, in order: environment variables, workload identity, managed identity, then developer tools (Visual Studio, Azure CLI, Azure PowerShell, azd, and interactive broker options where enabled). That chain is great locally and convenient everywhere, but in production it can pick the wrong credential or add start-up latency while probing. Two common hardening steps:

  • Set AZURE_TOKEN_CREDENTIALS=prod (supported in recent Azure.Identity versions) or exclude developer credentials, or
  • Use ManagedIdentityCredential directly in production and DefaultAzureCredential only in Development.

4. The Key Vault configuration provider

Azure.Extensions.AspNetCore.Configuration.Secrets adds Key Vault as a configuration source. Secret names use -- for the : hierarchy separator (Stripe--ApiKey becomes Stripe:ApiKey). Important behaviours:

  • Secrets are loaded at start-up; if the vault is unreachable, start-up fails (fail fast, which is usually what you want).
  • ReloadInterval re-reads secrets on a timer; combined with IOptionsMonitor<T> the app picks up rotated values without a restart.
  • Configuration providers are layered, so put Key Vault after appsettings.json and environment variables so it wins.
  • A KeyVaultSecretManager subclass can filter by prefix when several apps share a vault (better: don't share vaults).

Alternative for App Service and Functions: Key Vault references in app settings (@Microsoft.KeyVault(SecretUri=...)), resolved by the platform. No code, but rotation depends on the platform's refresh behaviour (it re-fetches periodically and on restart), and local development needs another source.

5. Access control on the vault

  • Use the Azure RBAC permission model, not legacy access policies.
  • Assign Key Vault Secrets User (read) to the app's identity at the vault scope; humans get Key Vault Secrets Officer through PIM, just in time.
  • One vault per app per environment keeps blast radius small; vaults are free, operations are cheap.
  • Enable soft delete and purge protection, private endpoints for sensitive environments, and diagnostic logs to Log Analytics to audit who read what.

6. Local development without secrets in the repo

 dotnet user-secrets init          # adds <UserSecretsId> to the csproj
 dotnet user-secrets set "Stripe:ApiKey" "sk_test_..."

User secrets are plain JSON in the user profile: kept outside the repo, not encrypted. They're loaded only when the environment is Development (the default builder calls AddUserSecrets for that environment). For shared dev resources, a better option is a dev Key Vault where developers have read access through an Entra group, so nobody copies keys around in chat.

7. Keeping secrets out of everything else

Leak path Control
Git commits GitHub secret scanning with push protection, gitleaks pre-commit / CI
CI logs Pipeline secret variables are masked; never echo them; use workload identity federation instead of stored service principal secrets
Container images No ENV or ARG with secrets; BuildKit --secret mounts for build-time needs
Application logs Never log configuration objects; redaction (see the logging question)
Crash dumps Treat dumps as sensitive; restrict and expire them

8. Rotation basics

  • Versioned secrets: Key Vault keeps versions; the app reads the latest.
  • Two-key overlap for third-party keys: add the new key, deploy/reload, then revoke the old one.
  • Event Grid SecretNearExpiry events can trigger a rotation Function.
  • Track expiry dates; a secret without an owner and an expiry is a future incident.

Try it yourself

  1. In a new Web API, run dotnet user-secrets init, set a value, and find the JSON file on disk. Note that it's plaintext.
  2. Create a dev Key Vault with RBAC, give yourself Key Vault Secrets User, add Demo--Message, and load it with AddAzureKeyVault and DefaultAzureCredential.
  3. Change the secret in the portal and watch IOptionsMonitor<T>.OnChange fire after the reload interval.
  4. Switch a SQL connection string to Authentication=Active Directory Default and create a contained user FROM EXTERNAL PROVIDER for your identity.
  5. Run gitleaks detect on one of your repositories and look at the history, not just the current tree.

💻 Code

Program.cs: Key Vault as a configuration source with a managed identity in production and the developer's own sign-in locally:

using Azure.Core;
using Azure.Identity;

var builder = WebApplication.CreateBuilder(args);

// Production: only the managed identity. Development: the developer's Azure CLI / VS sign-in.
TokenCredential credential = builder.Environment.IsDevelopment()
    ? new DefaultAzureCredential()
    : new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);

if (builder.Configuration["KeyVault:Uri"] is { Length: > 0 } vaultUri)
{
    builder.Configuration.AddAzureKeyVault(
        new Uri(vaultUri),
        credential,
        new Azure.Extensions.AspNetCore.Configuration.Secrets.AzureKeyVaultConfigurationOptions
        {
            // Pick up rotated secrets without a restart.
            ReloadInterval = TimeSpan.FromMinutes(5)
        });
}

builder.Services.AddOptions<StripeOptions>()
    .Bind(builder.Configuration.GetSection(StripeOptions.Section))
    .ValidateDataAnnotations()
    .ValidateOnStart(); // fail at start-up, not on the first payment

var app = builder.Build();
app.Run();

public sealed class StripeOptions
{
    public const string Section = "Stripe";

    [System.ComponentModel.DataAnnotations.Required]
    public string ApiKey { get; init; } = ""; // Key Vault secret name: Stripe--ApiKey
}

appsettings.json holds identifiers only; the SQL connection uses Entra auth, so there is no password at all:

{
  "KeyVault": { "Uri": "https://kv-claims-prod-aue.vault.azure.net/" },
  "ConnectionStrings": {
    "Claims": "Server=tcp:sql-claims-prod.database.windows.net;Database=Claims;Authentication=Active Directory Default;Encrypt=True"
  }
}

Grant the app read access and create its database user:

az role assignment create --assignee <app-principal-id> \
  --role "Key Vault Secrets User" \
  --scope $(az keyvault show -n kv-claims-prod-aue --query id -o tsv)
CREATE USER [app-claims-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [app-claims-prod];
ALTER ROLE db_datawriter ADD MEMBER [app-claims-prod];

⚠ Common mistakes

  • Mistake: Committing real keys in appsettings.Development.json or launchSettings.json because "it's only dev". Why it is wrong: Git history keeps them forever, dev keys often reach shared or production resources, and forks copy them. Instead: Use dotnet user-secrets or a dev Key Vault, and turn on push protection.
  • Mistake: Storing a secret in Key Vault and then storing the Key Vault client secret in appsettings. Why it is wrong: You've moved the problem, not solved it; the client secret is now the key to everything. Instead: Authenticate to Key Vault with managed identity or workload identity federation.
  • Mistake: Putting every secret into Key Vault without asking whether it needs to exist. Why it is wrong: Each secret still needs rotation and can still leak from memory or logs. Instead: Replace SQL passwords, storage keys and Service Bus SAS with managed identity and RBAC first.
  • Mistake: Sharing one vault across apps and environments. Why it is wrong: Any app with read access can read every other app's and every environment's secrets. Instead: One vault per app per environment, with Key Vault Secrets User scoped to that vault.
  • Mistake: Using DefaultAzureCredential in production without thought. Why it is wrong: It can probe several credential types, slowing start-up, and may pick an unintended identity. Instead: Use ManagedIdentityCredential (or restrict the chain) in production.
  • Mistake: Believing user secrets are encrypted. Why it is wrong: They're plaintext JSON in the user profile, readable by anything running as that user. Instead: Use them only for low-value dev credentials; use a dev vault for anything shared.
  • Mistake: Reading Key Vault on every request with SecretClient. Why it is wrong: It adds latency, hits Key Vault throttling limits, and makes the vault a hard per-request dependency. Instead: Load through configuration at start-up with a reload interval, or cache.
  • Mistake: Logging the bound options object or the full configuration at start-up. Why it is wrong: Secrets end up in Application Insights, visible to everyone with log access. Instead: Log only non-secret settings and use redaction.

🏛 Senior insight: trade-offs

Secrets management is mostly an elimination exercise. Count the secrets in a service's configuration, then ask of each one "could an identity replace this?" In Azure the answer is usually yes for everything Microsoft hosts, which leaves a handful of third-party credentials (payment gateways, email providers, partner APIs) that only accept keys. Those get Key Vault, an owner, an expiry and an automated rotation: an Event Grid SecretNearExpiry event triggers a Function that creates a new key at the provider, stores it as a new version, and the app's reload interval picks it up before the old key is revoked. Rotation that needs a coordinated redeploy across five teams won't happen on schedule; that operational friction is the most common reason secrets live for years.

Be honest about the costs. Managed identity and Key Vault put Entra token issuance and the vault on your start-up path: if a private endpoint's DNS is wrong or the vault is throttled (Key Vault has per-vault transaction limits), the app fails to start. Loading through configuration once, caching, and failing fast at start-up keeps that dependency out of the per-request path. A senior engineer also thinks about the non-runtime paths: CI service principals (replace with workload identity federation), Terraform state, container build args, crash dumps.

Measure it: number of long-lived secrets per service, secrets with no expiry date, mean time to rotate, and push-protection blocks per month.

Option When it fits Cost When not to
Managed identity Target is an Azure service with Entra auth RBAC setup, DB users, token endpoint dependency Third-party APIs that only take keys
Key Vault config provider App needs secrets via IOptions with reload Start-up dependency, throttling limits Per-request dynamic secret retrieval
App Service Key Vault references Simple App Service / Functions apps Platform-controlled refresh timing Local dev, containers outside App Service
User secrets Local development Plaintext on the laptop Anything shared or production

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the Key Vault configuration provider or reload intervals. Why: Checks the candidate can carry a whole service's settings into Key Vault and App Configuration, including rotation and refresh.
    How to answer

    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.

  2. When: Candidate mentions user secrets or local development. Why: Checks the candidate notices secrets in launch profiles and knows where local values belong.
    How to answer

    Properties/launchSettings.json defines launch profiles for local development: how to start the app, which URLs, and which environment variables. Visual Studio, Rider, VS Code with C# Dev Kit and dotnet run all read it, but it is not published. In this file I would flag: secrets are committed (a production connection string and API key), so they must be rotated now and moved to user secrets; the environment is Production, which switches on production behaviour and turns off user secrets, and combined with the production connection string means a developer's F5 talks to the live database; and it binds to 0.0.0.0 over plain HTTP, exposing the app to the network. I would replace it with HTTPS and HTTP profiles on localhost using Development, and add a separate production-like profile only if someone needs to test production behaviour against non-production resources.

  3. When: Candidate says managed identity removes the need for secrets. Why: Checks deeper understanding of managed identity as a caller to your own APIs, not just to Azure resources.
    How to answer

    Register the API in Entra ID with an App ID URI, delegated scopes (Orders.Read) for user calls and app roles (Orders.Read.All) for application calls. Register each client separately and grant it those permissions. In the API, AddMicrosoftIdentityWebApi (Microsoft.Identity.Web) wires up JWT bearer validation against your tenant.

    • A user token carries scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.
    • To call a downstream API as the user, use on-behalf-of: EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.
    • A managed identity caller requests api://<app-id>/.default; you assign it an app role.

    The trade-off: Entra does the heavy lifting, but permissions and consent live in the portal, so manage them as code.

↩ Usually asked after

More in Senior Security Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me