Secrets Management
Advanced
20 min read
Lesson 6 of 6
What are Secrets?
Secrets are sensitive data like passwords, API keys, connection strings, and certificates that must be kept confidential.
Secure Storage Options
1. Environment Variables
// Set environment variable
// Windows: setx MySecret "my-value"
// Linux: export MySecret="my-value"
// Access in code
string secret = Environment.GetEnvironmentVariable("MySecret");
2. User Secrets (Development)
// Initialize user secrets
dotnet user-secrets init
// Set secret
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=localhost;..."
// In Program.cs
builder.Configuration.AddUserSecrets<Program>();
3. Azure Key Vault (Production)
// Install package
dotnet add package Azure.Security.KeyVault.Secrets
// Configure Key Vault
builder.Configuration.AddAzureKeyVault(
new Uri("https://myvault.vault.azure.net/"),
new DefaultAzureCredential());
4. AWS Secrets Manager
// Install package
dotnet add package AWSSDK.SecretsManager
// Retrieve secret
using (var client = new AmazonSecretsManagerClient())
{
var request = new GetSecretValueRequest
{
SecretId = "my-secret"
};
var response = await client.GetSecretValueAsync(request);
string secret = response.SecretString;
}
Best Practices
- Never hardcode secrets in code or configuration files
- Use different secrets for development and production
- Rotate secrets regularly
- Restrict access to secrets
- Audit secret usage regularly
- Use secret scanning in your repository
Complete Example
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Configure multiple secret sources
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>();
// Configure Key Vault for production
if (builder.Environment.IsProduction())
{
builder.Configuration.AddAzureKeyVault(
new Uri("https://myvault.vault.azure.net/"),
new DefaultAzureCredential());
}
// Register services with secrets
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
// Use in code
public class ProductService
{
private readonly IConfiguration _configuration;
public ProductService(IConfiguration configuration)
{
_configuration = configuration;
}
public string GetApiKey()
{
return _configuration["ApiSettings:ApiKey"];
}
}
Key Takeaway
Never store secrets in code. Use environment variables, user secrets, or secure vault services.