IC Improve Code Recipes

Recipe 6.5 · C#

Getting Connection Strings Out of Source Code

Problem

Connection strings with SQL logins and passwords are compiled into classes, pasted into console tools and copied between projects. Some of them point at production. Removing them feels risky because nobody is sure which code still uses which string.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: credentials in source control, forever.
public static class Db
{
    public const string Conn =
        "Server=PRODSQL01;Database=Billing;" +
        "User Id=sa;Password=Summer2014!;";
}

The improved recipe

Find every connection string, move it to configuration under ConnectionStrings, prefer passwordless authentication, and add a startup guard that refuses to run in production with a password read from a JSON file. The guard uses Microsoft.Data.SqlClient.

PowerShell
# Find candidates in a working copy (review every hit by hand).
Get-ChildItem -Recurse -Include *.cs,*.config,*.json,*.ps1 |
    Select-String -Pattern 'Password\s*=|Pwd\s*=|User ID\s*=' |
    Select-Object Path, LineNumber, Line
C#
using System;
using System.Linq;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Hosting;

namespace ImproveCode.Configuration;

public static class ConnectionStringGuard
{
    /// <summary>Reads a connection string, checks that it parses,
    /// and refuses passwords stored in JSON files outside
    /// Development.</summary>
    public static string GetRequired(
        IConfiguration configuration,
        IHostEnvironment environment,
        string name)
    {
        string? value = configuration.GetConnectionString(name);
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new InvalidOperationException(
                $"Connection string '{name}' is missing. Set " +
                $"ConnectionStrings__{name} or a user secret.");
        }

        // Throws ArgumentException for a malformed string.
        var builder = new SqlConnectionStringBuilder(value);

        if (!environment.IsDevelopment()
            && !string.IsNullOrEmpty(builder.Password)
            && ComesFromJsonFile(configuration, name))
        {
            throw new InvalidOperationException(
                $"Connection string '{name}' contains a password and " +
                "is stored in a JSON file. Move it to a secret store.");
        }

        if (string.IsNullOrEmpty(builder.ApplicationName)
            || builder.ApplicationName.Contains("SqlClient"))
        {
            builder.ApplicationName = environment.ApplicationName;
        }

        return builder.ConnectionString;
    }

    /// <summary>Server and database only, safe to log.</summary>
    public static string Describe(string connectionString)
    {
        var builder = new SqlConnectionStringBuilder(connectionString);
        return $"{builder.DataSource}/{builder.InitialCatalog}";
    }

    private static bool ComesFromJsonFile(
        IConfiguration configuration, string name)
    {
        if (configuration is not IConfigurationRoot root)
        {
            return false;
        }

        string key = $"ConnectionStrings:{name}";
        IConfigurationProvider? source = root.Providers
            .Reverse()
            .FirstOrDefault(p => p.TryGet(key, out _));
        return source is JsonConfigurationProvider;
    }
}

The JSON file keeps only a passwordless default:

JSON
{
  "ConnectionStrings": {
    "AppDb": "Server=localhost;Database=AppDb;Integrated Security=true"
  }
}

Usage in Program.cs, with the factory from Chapter 1, Recipe 1.1:

C#
string cs = ConnectionStringGuard.GetRequired(
    builder.Configuration, builder.Environment, "AppDb");
builder.Services.AddSingleton<IDbConnectionFactory>(
    new SqlConnectionFactory(cs));

How it works

The search script is deliberately crude. It finds Password=, Pwd= and User ID= in code, config and scripts, and you review each hit. In my experience the list is longer than anyone expects, and the oldest hits are in console tools and SSIS script tasks that nobody remembers.

GetConnectionString("AppDb") reads ConnectionStrings:AppDb from any source: JSON, user secrets, an environment variable named ConnectionStrings__AppDb, or a Key Vault secret named Billing--ConnectionStrings--AppDb with the Recipe 6.4 prefix manager. Code that consumes the string doesn't change when the value moves between those homes.

Parsing with SqlConnectionStringBuilder turns a typo (Sever=) into an exception at startup instead of at the first query. Setting ApplicationName makes the app visible by name in sys.dm_exec_sessions and in SQL Server traces, which your DBA will thank you for during the next blocking investigation.

The guard enforces the policy in code. A production deployment where someone pasted a password into appsettings.Production.json fails with a clear message. The same string supplied through an environment variable or Key Vault passes. Development is exempt so local setups stay simple.

Describe gives you a safe string for logs and health checks. Logging the full connection string is one of the most common ways passwords leak into log files.

Variations and pitfalls

  • The best password is no password. On a Windows domain, run the app pool or service under a domain or group managed service account and use Integrated Security=true. In Azure, use a managed identity with Authentication=Active Directory Managed Identity (or Active Directory Default). Check the Microsoft.Data.SqlClient release notes for your version to see whether Entra ID authentication needs an extra package.
  • Moving a password out of the code doesn't remove it from the repository history. Treat every password that was ever committed as leaked and rotate it.
  • Microsoft.Data.SqlClient 4.0 and later encrypt connections by default. For a local or test server without a trusted certificate, add TrustServerCertificate=true in the development connection string only. In production, install a proper certificate.
  • Give each application its own login with only the permissions it needs. A shared sa login is how one compromised intranet page becomes a compromised server.
  • Keep one connection string per database per application. If five projects need the same database, they each read ConnectionStrings:AppDb from their own configuration.