Lesson 4 of 8
User Secrets & Azure Key Vault
User Secrets store development credentials (connection strings, API keys) outside your project directory - never committed to git. In production, Azure Key Vault or AWS Secrets Manager provides secure, audited secret storage with rotation capabilities.
User Secrets Setup
# ━━ User Secrets - development only, NEVER in git ━━
# Initialize User Secrets for your project
dotnet user-secrets init --project MyApp.Api
# Set secrets - stored in %APPDATA%/Microsoft/UserSecrets/{guid}/secrets.json
# NEVER in your project directory
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=localhost;Database=MyApp;User=sa;Password=DevPassword123!"
dotnet user-secrets set "Jwt:SecretKey" "my-super-secret-key-with-32-chars-minimum!"
dotnet user-secrets set "Email:SmtpPassword" "dev-smtp-password"
# List all secrets
dotnet user-secrets list
# Remove a secret
dotnet user-secrets remove "Jwt:SecretKey"
// In Program.cs - automatically loaded in Development environment
// (WebApplication.CreateBuilder does this automatically)
// In code - access the same way as appsettings.json:
// builder.Configuration["ConnectionStrings:DefaultConnection"]
// ━━ Azure Key Vault in production ━━
// dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
// dotnet add package Azure.Identity
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{builder.Configuration["KeyVault:VaultName"]}.vault.azure.net/"),
new DefaultAzureCredential()); // uses Managed Identity in Azure - no credentials in code!
// Key Vault secret naming convention:
// appsettings: ConnectionStrings:DefaultConnection
// Key Vault: ConnectionStrings--DefaultConnection (double dash = colon)
// ━━ Environment variables in Docker/Kubernetes ━━
// docker run -e "ConnectionStrings__DefaultConnection=Server=prod-db;..." myapp
// K8s secret mounted as env var - same override mechanismTip
Tip
Practice User Secrets Azure Key Vault in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of User Secrets Azure Key Vault from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with User Secrets Azure Key Vault is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?