Course contentsShow
← C#
Lesson 1104 of 1,90810. Entity Framework Core ModelingFree lesson

Managing Sensitive Data

Secure database connection strings and secrets using secure storage or vaults.

Managing Sensitive Data: Securing Connection Strings

In this lesson, you will learn how to protect your database credentials by moving them out of your source code and into secure storage providers.

When working with Entity Framework Core, it is tempting to hardcode your database connection string directly into your DbContext or appsettings.json file. However, if that file is committed to source control (like GitHub), your credentials become visible to anyone with repository access. Even if your repo is private, it is a significant security risk to store secrets in plain text.

The Secret Manager Approach

During development, the most effective tool is the .NET Secret Manager. This tool keeps sensitive data outside of your project directory, storing it in your local user profile folder.

  1. Initialize Secrets: Navigate to your project folder in your terminal and run dotnet user-secrets init. This creates a secrets.json file on your machine, not in your project.
  2. Set the Secret: Run dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=myServer;Database=myDb;User=myUser;Password=myPassword;".
  3. Accessing in EF Core: Since the Secret Manager automatically adds its storage to the IConfiguration provider in ASP.NET Core, you can simply use the standard GetConnectionString method in your Program.cs:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(connectionString));

Transitioning to Production

While Secret Manager works for development, production environments require centralized management. Instead of local JSON files, you should use a Vault service (such as Azure Key Vault, AWS Secrets Manager, or HashiCorp Vault).

By using the Azure.Extensions.Configuration.Secrets NuGet package, your application can fetch these secrets at runtime. Your Program.cs simply points to the vault URL, and the actual connection string is never stored on the server disk or in environment variables where it could be leaked through logs or process dumps.

By decoupling your connection string from your codebase, you ensure that your infrastructure can rotate credentials without requiring a code change or a new deployment.

Key Takeaway: Never store credentials in plain text; use the Secret Manager for local development and transition to a dedicated cloud-based vault for production secrets.