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

📚 Interview question

Your team has secrets and environment-specific settings scattered across appsettings.json files and portal app settings. How would you move them into Azure Key Vault and Azure App Configuration using managed identity, and how do you handle secret rotation, caching and refresh, start-up failures and feature flags?

A real-world migration of ASP.NET Core configuration to Azure Key Vault and Azure App Configuration with managed identity: inventory and classification, RBAC roles, AddAzureKeyVault versus App Configuration Key Vault references, labels per environment, sentinel-key refresh and Key Vault reload intervals, rotation with overlapping secret versions, passwordless Entra ID auth, start-up resilience and replicas, feature flags with Microsoft.FeatureManagement, and the rollout plan.

Senior RealWorldScenario Advanced aspnet-core azure-app-configuration azure-key-vault configuration feature-flags managed-identity

🎯 Key points

  • Inventory and classify every setting: secret, environment-specific, shared, restart-only or live
  • Managed identity with least-privilege RBAC (Key Vault Secrets User, App Configuration Data Reader), no client secrets
  • Prefer no secret at all: passwordless Entra ID auth to Azure SQL, Storage and Service Bus
  • App Configuration holds settings with a label per environment and Key Vault references for secrets, resolved with the app's own identity
  • Refresh with a sentinel key, SetRefreshInterval and the UseAzureAppConfiguration middleware; Key Vault values with a refresh interval
  • Rotate with overlapping secret versions or two keys so old and new both work during the refresh window
  • Start-up resilience: a start-up timeout, replicas in Australia East and Southeast, and a deliberate fail-fast or optional choice per source
  • Feature flags with Microsoft.FeatureManagement and IFeatureManager; roll out service by service behind ValidateOnStart

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd treat it as a migration, not a library swap. Step one is an inventory: every key in every appsettings file and every portal setting, classified as secret or not, per-environment or shared, restart-only or live. That usually shows half the 'secrets' don't need to exist: the SQL password, the storage key and the Service Bus connection string can all go away with managed identity and Entra ID auth. What's left, third-party API keys and SMTP credentials, goes into Key Vault, one vault per environment, with the app's managed identity granted only Key Vault Secrets User.

Non-secret settings and feature flags go into App Configuration, with one store and a label per environment, and secrets appear there as Key Vault references that the app resolves with its own identity. In the app I call AddAzureAppConfiguration, connect with the managed identity, select unlabelled keys plus the environment's label, register a sentinel key with refreshAll, set a refresh interval of about 30 seconds, and add the UseAzureAppConfiguration middleware so refresh is triggered by traffic. Live settings are read through IOptionsMonitor; restart-only ones stay IOptions.

For example, at [company] we migrated [eight] services this way. Rotation used to mean a deployment and an outage window; afterwards we added a new secret version, waited one refresh interval plus a margin, then disabled the old one, with zero downtime. The thing people miss is start-up: the app now depends on two network services before it can serve. So I set a start-up timeout, use App Configuration replicas in Australia East and Southeast, and decide per source whether a failure should stop the app or fall back. Moving secrets is easy; designing refresh, rotation and failure behaviour is the senior part."


Where each kind of setting goes

Kind Destination Why
Azure resource credentials (SQL, Storage, Service Bus) Nowhere: managed identity, Entra ID auth No secret to leak or rotate
Third-party secrets (Stripe, SMTP) Key Vault, referenced from App Configuration Encrypted, RBAC, audit, versions
Shared non-secret settings App Configuration, no label One place, change history
Per-environment settings App Configuration, label = environment Same keys, different values
Operational switches App Configuration feature flags Change live, targeting, audit
Safe defaults appsettings.json App still has sensible values offline

Refresh and rotation

Concern Mechanism
Settings change Update the keys, then bump the sentinel; the next refresh reloads everything
Refresh trigger UseAzureAppConfiguration middleware (web) or IConfigurationRefresher.TryRefreshAsync (workers)
Secret refresh Key Vault reference secret refresh interval, or ReloadInterval with AddAzureKeyVault
Rotation New version enabled, wait longer than the refresh interval, disable the old one
Long-lived objects Rebuild clients on change (IOptionsMonitor.OnChange) or read per use

Production example

After the migration, a leaked SMTP credential was rotated in [12 minutes] without a deployment: a new Key Vault version, a sentinel bump, confirmation in logs that all instances had reloaded, then the old version disabled. Previously the same change had needed a release and a [30-minute] maintenance window.

🔍 What the interviewer is checking

Checks whether the candidate can design and run a secrets and configuration migration end to end, including the parts that fail in production.

Green flags

  • Starts with an inventory and removes secrets through managed identity before vaulting the rest.
  • Explains sentinel refresh, refresh intervals and how values reach code through IOptionsMonitor.
  • Describes zero-downtime rotation with overlapping versions.
  • Plans for start-up failure, quotas, replicas and disaster recovery (soft delete, purge protection, a rehearsed restore), and rolls out service by service.
  • Adds auditing and alerting on secret access and configuration changes after the move.

Red flags

  • Uses a connection string or client secret to reach Key Vault.
  • Thinks storing secrets in Key Vault means rotation is automatic for the app.
  • Has no answer for what happens when App Configuration is unreachable.

📚 Learn in depth

1. The target architecture

                    +---------------------------+
                    |  App Configuration store  |   labels: (none), Test, Production
  app (managed  --->|  settings + feature flags |   Key Vault references for secrets
  identity)         +-------------+-------------+
      |                           | reference (URI only)
      |                           v
      +------------------> Key Vault (per environment)   RBAC: Key Vault Secrets User
      |
      +------------------> Azure SQL / Storage / Service Bus   Entra ID auth, no secret

The app resolves Key Vault references itself, so App Configuration never sees secret values, and access to secrets stays governed by Key Vault RBAC and audit logs.

2. Identity and roles

  • System-assigned identity is tied to one resource; user-assigned identity can be shared and created before the app, which suits infrastructure as code.
  • Roles: App Configuration Data Reader on the store, Key Vault Secrets User on the vault, database users created FROM EXTERNAL PROVIDER for SQL.
  • In production use ManagedIdentityCredential (or restrict DefaultAzureCredential) so start-up does not probe several credential types; locally developers use DefaultAzureCredential with their own login.

3. How refresh works

request -> UseAzureAppConfiguration middleware
             | interval elapsed?
             v
        GET sentinel key (cheap, one request)
             | changed?
             v
        reload all selected keys -> IConfiguration change token -> IOptionsMonitor rebuilds

Refresh is triggered by activity, and it is non-blocking for the request. Watching a single sentinel avoids one request per key, which matters for the store's request quotas. Workers without HTTP traffic call IConfigurationRefresher.TryRefreshAsync on a timer.

4. Rotation without downtime

t0  add secret version v2 (v1 still enabled)
t1  apps refresh (secret refresh interval) -> now use v2
t2  wait > refresh interval + margin; confirm via logs or metrics
t3  disable v1 at the provider

For third-party keys that allow two active keys (Stripe, storage keys), alternate between key A and key B. Clients built once at start-up (an SMTP client, an SDK client holding the key) must be rebuilt on change, or the new value never reaches them.

5. Start-up failure modes

  • App Configuration or Key Vault unreachable at start-up: by default AddAzureAppConfiguration throws, and the app fails to start. That is right for required secrets and wrong if it turns a regional blip into a full outage. Options: a start-up timeout, optional: true with safe defaults for non-critical settings, and replicas (Australia East primary, Southeast replica).
  • Throttling: thousands of instances starting at once all read every key. Selecting only needed keys and labels and using a sentinel keeps request counts down.

6. Rollout

  1. Infrastructure as code for the store, vault, identities and roles.
  2. One service at a time: add providers, keep the old values as fallback for one release, compare GetDebugView (masked) between old and new.
  3. Remove values from appsettings and the portal; rotate every secret that was ever committed.
  4. Add secret scanning and ValidateOnStart to the template.

Try it yourself

  1. Create an App Configuration store and a Key Vault in Australia East, add a Key Vault reference, and read it from a local app with your own login.
  2. Register a sentinel, change a value, bump the sentinel, and time how long the app takes to see the change.
  3. Add a feature flag and toggle it while sending requests.
  4. Block network access to the store and observe start-up with and without optional: true.
  5. Rotate a secret by adding a version and confirm the app switches within the refresh interval.

💻 Code

Program.cs for a service using App Configuration with Key Vault references, sentinel refresh, feature flags and passwordless SQL.

// Packages: Microsoft.Azure.AppConfiguration.AspNetCore, Microsoft.FeatureManagement.AspNetCore, Azure.Identity
using Azure.Identity;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using Microsoft.FeatureManagement;

var builder = WebApplication.CreateBuilder(args);

// Locally: developer login. In Azure: the app's managed identity only, no credential probing.
Azure.Core.TokenCredential credential = builder.Environment.IsDevelopment()
    ? new DefaultAzureCredential()
    : new ManagedIdentityCredential();

builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect(new Uri(builder.Configuration["AppConfig:Endpoint"]!), credential)
        .Select(KeyFilter.Any, LabelFilter.Null)                        // shared values
        .Select(KeyFilter.Any, builder.Environment.EnvironmentName)     // environment overrides win
        .ConfigureKeyVault(kv =>
        {
            kv.SetCredential(credential);                               // resolve references as the app
            kv.SetSecretRefreshInterval(TimeSpan.FromMinutes(5));       // pick up rotated versions
        })
        .ConfigureRefresh(refresh => refresh
            .Register("Shop:Sentinel", refreshAll: true)                // bump this to reload everything
            .SetRefreshInterval(TimeSpan.FromSeconds(30)))
        .UseFeatureFlags(flags => flags.SetRefreshInterval(TimeSpan.FromSeconds(30)));
});

builder.Services.AddAzureAppConfiguration();
builder.Services.AddFeatureManagement();

builder.Services.AddOptions<CheckoutOptions>().BindConfiguration("Checkout").ValidateDataAnnotations().ValidateOnStart();

var app = builder.Build();
app.UseAzureAppConfiguration(); // triggers refresh on incoming requests

app.MapGet("/checkout/limits", async (
    Microsoft.Extensions.Options.IOptionsMonitor<CheckoutOptions> options,
    IFeatureManager features) =>
{
    var newFlow = await features.IsEnabledAsync("NewCheckoutFlow");
    return Results.Ok(new { options.CurrentValue.MaxItems, newFlow }); // CurrentValue: sees refreshed values
});

app.Run();

public sealed class CheckoutOptions
{
    [System.ComponentModel.DataAnnotations.Range(1, 500)] public int MaxItems { get; init; } = 100;
}
// appsettings.json: safe defaults and endpoints only; SQL is passwordless
{
  "AppConfig": { "Endpoint": "https://appcs-shop-aue.azconfig.io" },
  "ConnectionStrings": { "Default": "Server=tcp:sql-shop-aue.database.windows.net;Database=Shop;Authentication=Active Directory Default;Encrypt=True" },
  "Checkout": { "MaxItems": 100 }
}

⚠ Common mistakes

  • Mistake: Moving every secret into Key Vault without asking whether it needs to exist. Why it is wrong: You still have to rotate and protect credentials that managed identity could remove. Instead: Go passwordless for Azure services first; vault only what remains.
  • Mistake: Authenticating to Key Vault or App Configuration with a client secret or connection string. Why it is wrong: You've moved the problem: now that secret must be stored somewhere. Instead: Use managed identity with least-privilege RBAC roles.
  • Mistake: Watching every key for changes. Why it is wrong: It multiplies requests against the store's quotas and causes partial updates. Instead: Register one sentinel key with refreshAll: true and bump it after a set of changes.
  • Mistake: Forgetting UseAzureAppConfiguration or a refresher in workers. Why it is wrong: Nothing triggers refresh, so values never change. Instead: Add the middleware for web apps and call TryRefreshAsync on a timer in workers.
  • Mistake: Disabling the old secret version as soon as the new one is added. Why it is wrong: Instances still using the cached old value fail until they refresh. Instead: Wait longer than the refresh interval, confirm, then disable.
  • Mistake: Building SDK clients with the secret once at start-up and expecting rotation to work. Why it is wrong: The client keeps the old value. Instead: Rebuild clients on change or read the value per use.
  • Mistake: Making every remote source required without thinking about outages. Why it is wrong: A configuration service blip stops every instance from starting during a scale-out. Instead: Use replicas and start-up timeouts, and decide per source between fail-fast and optional with safe defaults.
  • Mistake: Leaving the old values in appsettings and portal settings "just in case". Why it is wrong: Two sources of truth, and the committed secrets are still exposed. Instead: Remove them after one release and rotate anything that was ever committed.

🏛 Senior insight: trade-offs

The migration is mostly about decisions, not code: what should not be a secret at all, what may change live, which source wins, and what happens when the configuration service is down. I write those down in an ADR and in infrastructure as code. I also keep the blast radius small: one vault per environment (and per application where teams differ), labels rather than separate stores for environments, and feature flags with an owner and an expiry so they don't become permanent configuration.

After the migration, configuration needs the same observability as code. I send Key Vault and App Configuration diagnostic logs to Log Analytics and alert on denied secret reads, unexpected readers and secrets near expiry (Key Vault raises Event Grid events for that). App Configuration's revision history and snapshots give an audit trail and a quick rollback for a bad change. For disaster recovery, Key Vault keeps soft delete and purge protection on, App Configuration has a replica in Australia Southeast, and the restore steps for both are rehearsed alongside the application runbook.

Option When it fits Cost When not to
AddAzureKeyVault directly One app, few secrets, no App Configuration Loads every secret in the vault unless filtered Many apps sharing a vault
App Configuration + Key Vault references Several services, labels, feature flags Two services to run and secure A single tiny app
Platform Key Vault references (App Service, Container Apps) No code changes, secrets as environment variables Restart to pick up changes Settings that must change live
Passwordless Entra ID Azure SQL, Storage, Service Bus Role and database user set-up Third-party APIs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions how developers get secrets locally. Why: Checks they know what user secrets are for and what they don't protect.
    How to answer

    User secrets (the Secret Manager) keep developer-only secrets out of the repository. dotnet user-secrets init adds a UserSecretsId to the project file, and dotnet user-secrets set "Stripe:ApiKey" "sk_test_..." writes the value to a plain-text secrets.json in your user profile (%APPDATA%\Microsoft\UserSecrets\<id> on Windows, ~/.microsoft/usersecrets/<id> on Linux and macOS).

    CreateBuilder loads them only in the Development environment, as a provider after the appsettings files, so code reads them like any other key.

    They are not encryption: anyone or anything running as you can read the file. In production use Azure Key Vault with managed identity, Key Vault references, or platform secrets, and passwordless Entra ID authentication where the service supports it. The trade-off: zero setup for developers, but no protection beyond "not in git".

  2. When: Candidate mentions values refreshing without a restart. Why: Checks they know which options interface sees refreshed values and the pitfalls of capturing them.
    How to answer

    All three give you the same bound options; they differ in lifetime and freshness.

    • IOptions<T>: singleton, built once on first .Value, never changes, no named options. The default for settings that need a restart anyway.
    • IOptionsSnapshot<T>: scoped, rebuilt once per request (per scope), supports Get(name). A request sees one consistent value. It can't go into singletons, and it rebinds on every request.
    • IOptionsMonitor<T>: singleton, CurrentValue is cached and rebuilt when the configuration change token fires, supports Get(name) and OnChange. Use it in singletons and BackgroundService.

    Changes only arrive if a provider reloads (JSON files, App Configuration refresh), never from environment variables. The trade-off: fresher values mean code that must cope with values changing under it.

🛠 Real-world problems: how you handle them

Migrating eight services from committed appsettings secrets to Key Vault and App Configuration
Situation
A [retail] platform of [eight] .NET services on Azure Container Apps in Australia East. SQL passwords, storage keys and third-party API keys lived in appsettings files and portal settings; rotating anything needed a release and a maintenance window, and an audit had flagged it against the ACSC Essential Eight.
Signals
Secret scanning found [23] credentials in git history; a rotation of the SMTP password took a [30-minute] window; configuration differed between environments in ways nobody could explain.
Investigation
Built an inventory of every setting from appsettings files, portal exports and Helm values; compared environments with masked GetDebugView output; identified which credentials could be replaced with managed identity (SQL, Storage, Service Bus) and which had to stay secrets.
Resolution
Created user-assigned identities and RBAC in Bicep, moved SQL, Storage and Service Bus to Entra ID auth, stored the remaining secrets in a vault per environment, and put settings and feature flags in one App Configuration store with environment labels and a sentinel key. Migrated one service per sprint, keeping old values as fallback for one release, then removed them and rotated every credential that had ever been committed.
Prevention
GitHub push protection and gitleaks in CI, ValidateOnStart in the service template, an ADR covering which source wins and start-up behaviour, alerts on Key Vault access failures and OptionsValidationException, and a rotation runbook tested every quarter.

How to tell it (STAR)

**S:** At [company], our [eight] services kept SQL passwords and API keys in appsettings files and portal settings, and an audit flagged it; every rotation needed a release and a maintenance window. **T:** I led moving configuration to Key Vault and App Configuration without downtime. **A:** I started with an inventory and found most secrets could disappear by switching SQL, Storage and Service Bus to managed identity. The rest went into Key Vault, referenced from App Configuration with environment labels and a sentinel key for refresh. We migrated one service per sprint behind ValidateOnStart, then rotated everything that had ever been committed and turned on push protection. **R:** Committed credentials went from [23] to zero, and rotations became a [12-minute] no-downtime task instead of a release.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me