How to Secure Your Secret Keys and Database Connections in .NET
User Secrets & Azure Key Vault Explained
Hi, I'm Steve Bang—a .NET developer with 5 years of experience. If there's one thing I've learned, it's that securing your secret keys and database connection strings is crucial for every project. If you store them carelessly, you risk leaking sensitive information, which can lead to security breaches, data loss, or even financial damage.
In this guide, I'll explain how to secure secrets in .NET applications. We'll use two powerful tools:
- User Secrets (for development)
- Azure Key Vault (for production)
This guide is beginner-friendly, packed with real-world advice, and demo code you can copy and adapt.
Why You Should NEVER Hardcode Secrets
Before we dive into the tools, let's discuss why hardcoding secrets is so dangerous.
What is a “secret”?
- Database connection strings
- API keys (for services like Stripe, Google, AWS, etc.)
- Passwords or tokens
The Problem with Hardcoding
Many beginners put secrets directly into their code, for example:
// BAD PRACTICE!
string connectionString = "Server=mydb;Database=mydb;User Id=admin;Password=SuperSecret123;";
This is dangerous because:
- If you upload code to GitHub, anyone with access can see your secrets.
- Even private repos are not 100% safe.
- Secrets should be easy to rotate/change without re-deploying code.
Best practice: Keep secrets outside of your source code!
Overview: How .NET Handles Secrets
.NET Core (and onwards) uses a configuration system that loads settings from multiple sources, including:
appsettings.json
- Environment variables
- User Secrets (for development)
- Azure Key Vault (for production)
This approach lets you use different secrets for development, testing, and production—without changing your code.
1. Storing Secrets in Development: User Secrets
When you’re building an app locally, you need a way to store secrets that:
- Aren’t in source control
- Can be shared safely between local projects
This is where User Secrets shine.
What are User Secrets?
User Secrets is a feature in .NET that lets you store secrets in a JSON file outside your project folder. This file is stored in your user profile directory, so it’s never checked into Git.
Tip: User Secrets are for development only. Never use them for production secrets!
How to Enable User Secrets
1. Only for projects with a project file (.csproj
) like ASP.NET Core, Console, etc.
2. In the project folder, run:
dotnet user-secrets init
This adds a UserSecretsId
to your .csproj
file:
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<UserSecretsId>your-guid-here</UserSecretsId>
</PropertyGroup>
3. Add a secret using the CLI:
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=.;Database=DevDb;User Id=sa;Password=devPassword;"
dotnet user-secrets set "MyApiKey" "test-api-key-123"
How Does .NET Load User Secrets?
When you run your app in Development mode, User Secrets automatically merge with your configuration.
You can access them exactly like you would from appsettings.json
:
string connStr = builder.Configuration.GetConnectionString("DefaultConnection");
string apiKey = builder.Configuration["MyApiKey"];
Where Are User Secrets Stored?
On Windows:
%APPDATA%\Microsoft\UserSecrets\<UserSecretsId>\secrets.json
On Linux/macOS:
~/.microsoft/usersecrets/<UserSecretsId>/secrets.json
This file is not in your project folder and is never checked into Git!
Example: Using User Secrets in ASP.NET Core
// Program.cs (ASP.NET Core 6+)
var builder = WebApplication.CreateBuilder(args);
// No extra code needed. User Secrets are loaded automatically in development.
var mySecret = builder.Configuration["MyApiKey"];
builder.Services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Good Practices with User Secrets
- Use User Secrets for anything sensitive during development.
- Never commit secrets to source control.
- Rotate/change secrets easily via CLI.
- Use environment variables or Key Vault for production.
2. Storing Secrets in Production: Azure Key Vault
User Secrets are great for local development, but you need something more secure and robust for production.
Enter Azure Key Vault.
What is Azure Key Vault?
Azure Key Vault is a cloud service that securely stores secrets, keys, and certificates.
- Highly secure (managed by Microsoft)
- Supports secret versioning and access control
- Easy integration with Azure and .NET apps
How to Use Azure Key Vault in .NET
Prerequisites
- You need an Azure subscription.
- Your app must be registered in Azure AD (for authentication).
- You must have a Key Vault created in Azure.
1. Create a Key Vault
- In the Azure Portal, search for Key Vault and create a new one.
- Give it a name (e.g.,
my-app-kv
). - Assign access policies (who can read/write secrets).
2. Store Secrets in Key Vault
In the Azure Portal:
- Go to your Key Vault → Secrets → Generate/Import
- Add secrets like
ConnectionStrings--DefaultConnection
,MyApiKey
, etc.
3. Give Your App Permission to Access Key Vault
- Use Managed Identity (highly recommended for Azure-hosted apps) or register an Azure AD App.
- Assign at least “Get” secret permissions to your app/service principal.
4. Integrate Azure Key Vault with .NET
Install the NuGet package:
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
Add Key Vault integration in your Program.cs
(ASP.NET Core 6+):
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
// Add Azure Key Vault to configuration
if (builder.Environment.IsProduction())
{
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{yourKeyVaultName}.vault.azure.net/"),
new DefaultAzureCredential());
}
Note:
DefaultAzureCredential
works seamlessly with Managed Identity in Azure, your Azure CLI login, or environment variables.
5. Access Secrets in Your App
Just like with User Secrets or appsettings.json
:
string connStr = builder.Configuration.GetConnectionString("DefaultConnection");
string apiKey = builder.Configuration["MyApiKey"];
Key Vault secret names with colons (:
) are converted to double dashes (--
)
e.g.,
- In Key Vault:
ConnectionStrings--DefaultConnection
- In code:
builder.Configuration.GetConnectionString("DefaultConnection")
6. Deploying to Azure
- When deploying, make sure your app has the right Managed Identity or Azure AD App registration with access to Key Vault.
- Test access by running your app in Azure and confirming it can read secrets.
Example: Real-World Secure Connection String
Never this:
// Hardcoded!
options.UseSqlServer("Server=prod;Database=prod;User=admin;Password=SuperSecret!");
Instead:
// Secure: Loaded from Key Vault or User Secrets
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
Frequently Asked Questions
Q. Can I use both User Secrets and Key Vault together?
A: Yes! In development, use User Secrets. In production, use Azure Key Vault.
.NET’s configuration system merges these sources automatically, using the most appropriate for each environment.
Q. What about environment variables?
A: Environment variables are another way to store secrets (especially in Docker or CI/CD).
You can use them in combination with User Secrets and Key Vault.
Q. How do I rotate/change secrets?
A:
- User Secrets: Use the CLI to update values.
- Key Vault: Update secrets in the Azure Portal (or CLI); your app picks up new values on restart.
Q. What if I accidentally commit a secret?
A:
- Change the secret immediately (in your database or API provider).
- Use tools like GitGuardian or TruffleHog to scan for leaked secrets.
Summary: Best Practices
- Never hardcode secrets in your codebase.
- Use User Secrets for local development.
- Use Azure Key Vault (or another secrets manager) for production.
- Access secrets via .NET Configuration, not directly.
- Rotate secrets regularly and limit who has access.
- Automate secret management with DevOps pipelines where possible.
- Monitor for accidental leaks (use security tooling).
Final Thoughts
Securing your secrets is not optional—it’s a must for your app’s security and your peace of mind.
By leveraging tools like User Secrets and Azure Key Vault, you can develop confidently, knowing your sensitive data is protected.
Start today:
- Try adding User Secrets to your dev project!
- Experiment with Azure Key Vault if you’re deploying to the cloud.