Search code examples
c#.net-coreasp.net-web-apijwt

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?


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);
    });