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

📚 Interview question

What are user secrets in .NET? Explain where they are stored, how they get loaded, why they are only for development, why they are not encryption, and what you use instead in production.

The .NET Secret Manager: UserSecretsId in the project file, dotnet user-secrets init/set/list, the secrets.json location on Windows, Linux and macOS, loading only in the Development environment, why it is plain text outside the repo rather than encryption, and production replacements such as Azure Key Vault with managed identity and platform secret stores.

Junior Theory Intermediate aspnet-core azure-key-vault configuration secrets-management user-secrets

🎯 Key points

  • dotnet user-secrets init adds a UserSecretsId GUID to the .csproj; set/list/remove manage values
  • Values live in plain-text secrets.json under %APPDATA%\Microsoft\UserSecrets\<id> on Windows or ~/.microsoft/usersecrets/<id> on Linux and macOS
  • The file sits outside the project folder, so it is never committed: that is the only protection
  • Not encrypted: any process running as the user can read it
  • CreateBuilder loads user secrets only when the environment is Development, after the appsettings files
  • Keys use the same : hierarchy, so code reads them exactly like any other configuration
  • Production uses Azure Key Vault with managed identity, Key Vault references or platform secrets, and passwordless Entra ID auth where possible

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

🗣 Full answer (senior)

How I would answer this in an interview

"User secrets solve one problem: stopping developers from committing their local API keys and connection strings. When I run dotnet user-secrets init, the project file gets a UserSecretsId GUID. dotnet user-secrets set then writes key-value pairs into a secrets.json file in my user profile, under that GUID, outside the source tree. WebApplication.CreateBuilder adds a user secrets provider, but only when the environment is Development, and it sits after appsettings.json and appsettings.Development.json, so a secret overrides a placeholder in the JSON. My code just reads Stripe:ApiKey from configuration and doesn't know where it came from.

The important thing is what it is not. It isn't encrypted and it isn't a vault: the file is plain JSON readable by any process running as me. It also doesn't exist on a server, which is exactly why it's Development-only. In production I use Azure Key Vault, loaded with AddAzureKeyVault and a managed identity, or Key Vault references in App Service and Container Apps that surface secrets as environment variables. Better still, for Azure SQL, Storage or Service Bus I use Entra ID authentication with the managed identity, so there's no secret to store at all.

The mistake I see is people treating user secrets as secure storage, copying secrets.json around on chat, or setting the environment to Development on a test server just so it reads secrets. User secrets keep secrets out of git; they don't keep them secret."


Commands

Command Effect
dotnet user-secrets init Adds <UserSecretsId> to the .csproj
dotnet user-secrets set "Stripe:ApiKey" "sk_test_123" Adds or updates a key
dotnet user-secrets list Prints all values (in plain text)
dotnet user-secrets remove "Stripe:ApiKey" / clear Deletes one / all
cat secrets.json \| dotnet user-secrets set Bulk import a JSON file

Where the file lives

OS Path
Windows %APPDATA%\Microsoft\UserSecrets\<UserSecretsId>\secrets.json
Linux / macOS ~/.microsoft/usersecrets/<UserSecretsId>/secrets.json

User secrets versus production options

Option Protection Where it fits
User secrets Outside git only; plain text Developer machines
Environment variables from the platform Visible to anyone with portal or kubectl access Non-critical values, or as the delivery of Key Vault references
Azure Key Vault + managed identity Encrypted at rest, RBAC, audit log, rotation Production secrets
Entra ID (passwordless) auth No secret exists Azure SQL, Storage, Service Bus, Key Vault itself

Production example

On a team of [eight] developers, each had their own Stripe test key and a local SQL password in user secrets, with placeholders like "ApiKey": "set-in-user-secrets" in appsettings.json so missing values were obvious. In Azure Australia East the same keys came from Key Vault through the app's managed identity, and the database connection used Authentication=Active Directory Managed Identity, so production had no SQL password at all.

🔍 What the interviewer is checking

Checks that the candidate understands what user secrets protect against and what they don't.

Green flags

  • States clearly that user secrets are plain text, outside the repo, Development only.
  • Knows UserSecretsId and the CLI commands.
  • Names Key Vault with managed identity, and passwordless auth, for production.
  • Commits placeholders, not values.

Red flags

  • Calls user secrets encrypted.
  • Suggests using user secrets on a server.
  • Has no plan for production secrets other than environment variables typed into the portal.

📚 Learn in depth

1. How the provider finds the file

The UserSecretsId in the project file is compiled into the assembly as [assembly: UserSecretsIdAttribute("...")] by the Microsoft.Extensions.Configuration.UserSecrets build targets. At run time, AddUserSecrets(assembly) reads that attribute and builds the path:

.csproj  <UserSecretsId>7f1c…</UserSecretsId>
   │ build
   ▼
assembly attribute UserSecretsIdAttribute("7f1c…")
   │ run (Development only)
   ▼
PathHelper.GetSecretsPathFromSecretsId("7f1c…")
   └─► ~/.microsoft/usersecrets/7f1c…/secrets.json  (JSON provider, reloadOnChange)

CreateBuilder calls AddUserSecrets with the entry assembly when IsDevelopment() is true and the attribute exists.

2. The file format

dotnet user-secrets set writes flattened keys:

{ "Stripe:ApiKey": "sk_test_123", "ConnectionStrings:Default": "Server=..." }

Nested JSON also works if you edit the file by hand (Visual Studio's Manage User Secrets opens it).

3. Why it is not security

There is no encryption and no access control beyond the file system. Malware, a browser extension or a sync tool running as you can read it. It also travels in profile backups. Its only guarantee is that the secret is not in the repository.

4. Using it outside ASP.NET Core

Console apps and tests can call new ConfigurationBuilder().AddUserSecrets<Program>(). Integration tests sometimes use it for local connection strings; CI should use pipeline secrets instead.

5. The production path

Developer laptop            Azure (Australia East)
────────────────            ───────────────────────
secrets.json                Key Vault ──RBAC──► managed identity of the app
   │                           │
   ▼                           ▼
IConfiguration["Stripe:ApiKey"]  (same key, different provider)

Key Vault secret names can't contain :, so the Key Vault provider maps -- to : (Stripe--ApiKey).

Try it yourself

  1. Run dotnet user-secrets init in a web project and open the .csproj to find the GUID.
  2. Set a secret, then open secrets.json in a text editor and confirm it is plain text.
  3. Run the app with ASPNETCORE_ENVIRONMENT=Production and confirm the secret is no longer read.
  4. Add a placeholder for the same key to appsettings.json and confirm the secret overrides it in Development.
  5. Use GetDebugView() to see the key reported against the user secrets JSON provider.

💻 Code

Local development with user secrets, production with Key Vault, and the same key read by code in both cases.

cd src/Shop.Api
dotnet user-secrets init
dotnet user-secrets set "Stripe:ApiKey" "sk_test_local_only"
dotnet user-secrets list

# Production: grant the app's managed identity read access to secrets only (least privilege)
az role assignment create --role "Key Vault Secrets User" \
  --assignee <managed-identity-principal-id> \
  --scope /subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.KeyVault/vaults/<vault>
// Program.cs
using Azure.Identity;

var builder = WebApplication.CreateBuilder(args); // loads user secrets automatically in Development

if (!builder.Environment.IsDevelopment())
{
    // Production: secrets from Key Vault through the app's managed identity, no secret needed to read secrets.
    // The identity needs only the "Key Vault Secrets User" role on this vault (RBAC permission model).
    var vaultUri = new Uri(builder.Configuration["KeyVault:Uri"]!);
    builder.Configuration.AddAzureKeyVault(vaultUri, new ManagedIdentityCredential());
}

builder.Services.AddOptions<StripeOptions>()
    .BindConfiguration(StripeOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart(); // fail at start-up if no provider supplied the key

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

public sealed class StripeOptions
{
    public const string Section = "Stripe";
    [System.ComponentModel.DataAnnotations.Required]
    public string ApiKey { get; init; } = "";
}

⚠ Common mistakes

  • Mistake: Calling user secrets "encrypted" or "secure storage". Why it is wrong: It is a plain-text JSON file in your profile, readable by anything running as you and copied into profile backups. Instead: Treat it as "not in git" and nothing more.
  • Mistake: Setting the environment to Development on a server so user secrets load. Why it is wrong: It also turns on the developer exception page and other dev behaviour, and the file still has to be copied there. Instead: Use Key Vault or platform secrets.
  • Mistake: Relying on user secrets in CI/CD pipelines or integration test agents. Why it is wrong: Build agents have no secrets.json, so people work around it by committing values or writing the file in a script that leaks into logs. Instead: Use the pipeline's secret store (GitHub Actions secrets, Azure DevOps variable groups linked to Key Vault) delivered as environment variables, or workload identity federation so no secret exists.
  • Mistake: Sharing secrets.json through chat or email to onboard people. Why it is wrong: The secret now lives in more systems with weaker controls. Instead: Give each developer their own test credentials, or a shared dev Key Vault they access with their own identity.
  • Mistake: Forgetting dotnet user-secrets init on a new project and wondering why nothing loads. Why it is wrong: Without UserSecretsId there is no file to read. Instead: Initialise once and commit the .csproj change.
  • Mistake: Storing production credentials in user secrets "to test against production". Why it is wrong: Production secrets end up on laptops, in backups and outside audit. Instead: Use a non-production environment, or access production through your own Entra ID identity.
  • Mistake: Putting real secrets in appsettings.Development.json because "it's only dev". Why it is wrong: That file is committed. Instead: Commit placeholders and keep values in user secrets.

🏛 Senior insight: trade-offs

User secrets are a convenience for keeping values out of git, not secure storage, so I treat them as the last resort rather than the default. Even the best secret store is second best to no secret. For Azure resources I push for managed identity with Entra ID auth (Azure SQL, Storage, Service Bus, Key Vault), and developers authenticate the same code with their own login through DefaultAzureCredential locally. What remains for user secrets is whatever cannot use identity, typically personal test keys for third-party APIs; anything shared by the team goes in a dev Key Vault that each developer reads with their own identity, so access is audited and revocable. Under the Privacy Act and the ACSC Essential Eight, fewer long-lived credentials means fewer things to rotate and fewer to leak, and a lost laptop holds nothing that unlocks production.

Option When it fits Cost When not to
User secrets Individual developer test keys None Shared or production secrets
Shared dev Key Vault + developer identity Team-wide dev secrets Azure setup and RBAC Offline development
Managed identity, passwordless Azure services in every environment Initial RBAC wiring Third-party APIs that only accept keys

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions keeping secrets out of launchSettings.json. Why: Checks they spot secrets committed in launchSettings.json and move them to user secrets.
    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.

  2. When: Candidate mentions Key Vault or managed identity for production. Why: Checks whether they can design the production side of secrets management, not just name it.
    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.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me