Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework Core support database password rotation

Scenario:

  1. Web Api application in NET Core 2.2, it is deployed on multiple containers.
  2. In Startup, I read from the database password from HashiCorp Vault and put it into my connection string.
  3. I add the Entity Framework Core context to the Service Collection.
  4. I use the context in multiple controllers.

If I change the database password in Vault, all the the requests to the database will fail due to authentication errors.

I can bring all the containers down and when they restart they will have the new password, but that is not what I want to do. There are a few hacky ways of getting around this problem but they involve not using the Service Collection and I want to use it.

Question:

Does EF Core support password rotation, or is there a way to achieve this while still using the Service Collection?

like image 568
Bryan Avatar asked Jun 16 '26 06:06

Bryan


2 Answers

You should be able to add the DbContext into DI and pass a delegate which creates the instance essentially taking control of the static nature of the connection string and work out the correct one at runtime.

services.AddScoped<YourDbContext>(svc =>
     {
         var connString = ... logic to get the conn string with the right password from HashiCorp vault;
         var dbContextOptions = new DbContextOptionsBuilder<YourDbContext>();
         dbContextOptions.UseSqlServer(connString); //Or w/e ef provider for db you use
         return new YourDbContext(dbContextOptions.Options);
     });
like image 158
Vidmantas Blazevicius Avatar answered Jun 17 '26 18:06

Vidmantas Blazevicius


Since the database password is read from HashiCorp vault during the start up, perhaps you could consider using healthcheck feature (https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-2.2) to set up a live health check endpoint.

Then use your container management tool to probe the endpoint and restart the container should it fails (i.e., unable to connect to the DB due to connection string being obsolete).

like image 34
frostshoxx Avatar answered Jun 17 '26 19:06

frostshoxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!