Secrets Management
Store secrets safely using .NET User Secrets in development and Azure Key Vault or environment variables in production.
Secrets Management is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Secrets Are Not Config
Passwords, API keys, connection strings, and JWT signing keys must never be stored in appsettings.json or committed to source control. .NET provides several purpose-built mechanisms for secrets management.
User Secrets (Development)
User Secrets store development secrets outside the project directory in a machine-local file. They are loaded automatically in the Development environment and never travel with the source code.
# Initialize (adds UserSecretsId to .csproj):
dotnet user-secrets init
# Set secrets:
dotnet user-secrets set "Database:Password" "dev-pass-123"
dotnet user-secrets set "Jwt:SigningKey" "dev-jwt-key-abc"
dotnet user-secrets set "OpenAI:ApiKey" "sk-..."
# List / remove:
dotnet user-secrets list
dotnet user-secrets remove "OpenAI:ApiKey"
# Stored at:
# macOS/Linux: ~/.microsoft/usersecrets/{id}/secrets.json
# Windows: %APPDATA%\Microsoft\UserSecrets\{id}\secrets.jsonLoading User Secrets Explicitly
Host.CreateApplicationBuilder automatically loads User Secrets in Development. You can also load them explicitly for non-Development scenarios or test projects.
var builder = Host.CreateApplicationBuilder(args);
// Automatic (Development only) — already done by default
// Equivalent manual call:
if (builder.Environment.IsDevelopment())
builder.Configuration.AddUserSecrets<Program>();
// In test projects (no ASPNETCORE_ENVIRONMENT):
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.AddUserSecrets<Program>() // loads secrets.json
.AddEnvironmentVariables()
.Build();Environment Variables for Production
In production, inject secrets as environment variables — they are read from the OS or container orchestrator at runtime and never persisted to disk in plaintext alongside code.
# docker-compose.yml — inject secrets:
services:
api:
image: myapp:latest
environment:
- Database__Password=${DB_PASSWORD} # from .env file
- Jwt__SigningKey=${JWT_KEY}
- ConnectionStrings__Default=Server=db;Password=${DB_PASSWORD}
# Kubernetes Secret:
kubectl create secret generic app-secrets \
--from-literal=Database__Password=secret123 \
--from-literal=Jwt__SigningKey=verylongkey
# Reference in pod spec:
# env:
# - name: Database__Password
# valueFrom:
# secretKeyRef: { name: app-secrets, key: Database__Password }Azure Key Vault Integration
Azure Key Vault is a managed secrets store for production. The official provider loads secrets directly into the configuration system — your app reads them like any other config value.
// dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
// dotnet add package Azure.Identity
var builder = WebApplication.CreateBuilder(args);
if (!builder.Environment.IsDevelopment())
{
var kvUri = new Uri(builder.Configuration["Azure:KeyVaultUri"]!);
// Uses Managed Identity / workload identity in production:
builder.Configuration.AddAzureKeyVault(kvUri, new DefaultAzureCredential());
}
// Secrets named "Database--Password" in Key Vault
// are accessible as builder.Configuration["Database:Password"]
// (Key Vault uses -- as the : separator)AWS Secrets Manager
On AWS, use the Amazon.Extensions.Configuration.SystemsManager or Secrets Manager directly to inject secrets into the .NET configuration pipeline.
// dotnet add package Amazon.Extensions.Configuration.SystemsManager
builder.Configuration.AddSystemsManager(
path: "/myapp/production", // parameter store prefix
optional: false,
reloadAfter: TimeSpan.FromMinutes(30));
// Or Secrets Manager directly:
using Amazon.SecretsManager;
using Amazon.SecretsManager.Model;
var client = new AmazonSecretsManagerClient();
var response = await client.GetSecretValueAsync(new GetSecretValueRequest
{
SecretId = "myapp/production/db-password"
});
var secret = response.SecretString; // JSON string
// Parse and inject into configHashiCorp Vault
HashiCorp Vault provides dynamic secrets, secret rotation, and fine-grained access control. Use the community VaultSharp library or a configuration provider to integrate with .NET.
// dotnet add package VaultSharp
using VaultSharp;
using VaultSharp.V1.AuthMethods.Token;
var authMethod = new TokenAuthMethodInfo("vault-token");
var vaultClient = new VaultClient(
new VaultClientSettings("https://vault.example.com:8200", authMethod));
// Read a secret:
var kv = await vaultClient.V1.Secrets.KeyValue.V2
.ReadSecretAsync(path: "myapp/database", mountPoint: "secret");
var password = kv.Data.Data["password"].ToString();
// Then store in configuration or pass to IOptions:
builder.Configuration["Database:Password"] = password;Protecting Secrets in Memory
Even in memory, secrets should be handled carefully. Use SecureString or limit scope with using blocks, and avoid logging secret values.
// NEVER log secrets:
_logger.LogInformation("API Key: {Key}", apiKey); // WRONG!
_logger.LogInformation("API Key configured: {HasKey}", !string.IsNullOrEmpty(apiKey)); // CORRECT
// Mask in diagnostics:
public string KeyHint => apiKey.Length > 8
? $"{apiKey[..4]}...{apiKey[^4..]}"
: "****";
// Scope the secret:
void ProcessWithSecret()
{
var secret = LoadSecret();
try { UseSecret(secret); }
finally { secret = string.Empty; } // clear reference
}Secrets in CI/CD
CI/CD pipelines (GitHub Actions, Azure DevOps, Jenkins) provide secret variable stores. Inject secrets as environment variables at build/deploy time — never hard-code them in pipeline YAML.
# GitHub Actions — store in Settings > Secrets:
# name: Deploy
# on: push
# jobs:
# deploy:
# runs-on: ubuntu-latest
# env:
# Database__Password: ${{ secrets.DB_PASSWORD }}
# Jwt__SigningKey: ${{ secrets.JWT_KEY }}
# steps:
# - name: Run migration
# run: dotnet ef database update
# Azure Pipelines:
# variables:
# - group: my-app-secrets # from Azure DevOps Variable Group
# The secrets are masked in logs and never stored in plaintextReal-World: Dev/Prod Secret Strategy
A complete secrets strategy: User Secrets in development, Azure Key Vault in production, with environment variables as fallback.
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
// Dev: local secrets.json, never committed
builder.Configuration.AddUserSecrets<Program>();
}
else
{
// Production: Azure Key Vault via Managed Identity
var kvUri = builder.Configuration["Azure:KeyVaultUri"];
if (!string.IsNullOrEmpty(kvUri))
builder.Configuration.AddAzureKeyVault(
new Uri(kvUri), new DefaultAzureCredential());
}
// Always load env vars (works in all environments + containers):
// Already loaded by CreateBuilder — they override Key Vault
// Bind secrets to strongly typed options:
builder.Services
.AddOptions<JwtOptions>()
.BindConfiguration("Jwt")
.ValidateDataAnnotations()
.ValidateOnStart();Quick Check
Why should secrets never be stored in appsettings.json?
Recap: Secrets Management
Key takeaways:
- Never store secrets in
appsettings.json— it gets committed to source control - Development: use User Secrets (
dotnet user-secrets) — stored outside the project - Production: environment variables, Azure Key Vault, AWS Secrets Manager, or HashiCorp Vault
- CI/CD: store secrets in the pipeline's secret store, inject as env vars
- Never log raw secret values; use hints or masks
- Combine strategies: User Secrets in dev + Key Vault in prod + env vars as override
Frequently asked questions
Is the “Secrets Management” lesson free?
Yes — the full text of “Secrets Management” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Secrets Management”?
Store secrets safely using .NET User Secrets in development and Azure Key Vault or environment variables in production. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Secrets Management” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.