Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically change database connection depending on jwt claim

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading