Search code examples
c#.netasp.net-core-mvcasp.net-core-6.0

.NET Core 6 : to protect potentially sensitive information in your connection string


How do I move sensitive information below into the 'The Secret Manager Tool'?

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Server=Test; column encryption setting=enabled;Database=Test;user id=User1;password='Password1';Trust Server Certificate=true");

I know I can right click on the solution name and select "Manage User Secrets", which then generates the secret Json file, but what I am pasting into this file?

And when I move this application over to the production server, do I copy & paste over the secret.json as well?

Thanks in advance.


Solution

  • You need to take a small step back and consider tools ASP.NET Core/.NET provides to work with configuration.

    From DbContext Lifetime, Configuration, and Initialization doc you can see that one of the common pattern is to use dependency injection and setup the the connection string on application startup. This will require adding constructor to the context (and modifying/removing OnConfiguring overload - docs):

    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
    

    And:

    builder.Services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer("ConnectionStringHere")); // or AddDbContextFactory
    

    Next step is to read the connection string from the settings:

    builder.Services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(builder.Configuration.GetConnectionString("ConnStringName"))); // or AddDbContextFactory
    

    Which will require connection string to be read from the configuration, for example from appsettting.json:

    {
      "ConnectionStrings": {
        "ConnStringName": "ACTUAL_CONNECTION_STRING"
      },
    }
    

    Also you can move connection string to any of the supported configuration providers, for example - Secret Manager (note, it is for development environment only, for other environments is better to use either environment variables or secured key storages).