Home > Software design >  Dynamically change database connection depending on jwt claim
Dynamically change database connection depending on jwt claim

Time:07-26

I want to dynamically change my database connection depending on the current client. Every client has a Claim in his JWT with the database string. In my Program.cs I create the database connection with the following line:

builder.Services.AddDbContext<My_Context>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Now I am trying to replace "DefaultConnection" with the individual Claim. Is there a possibility to get the Claim in the Program.cs file?

CodePudding user response:

You can get claims and create connection string dynamically like below:

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

builder.Services.AddDbContext<My_Context>((serviceProvider, dbContextBuilder) =>
{
    var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();

    // get required claim 
    var allClaims = httpContextAccessor.HttpContext.User.Claims;
    // filter whatever you need and build connectionstring based on claim
    var connectionString = getconnectionstring();
    dbContextBuilder.UseSqlServer(connectionString);
});
  • Related