如何在Dot Net Core 2.2,JWT中为每个用户创建DBContext / Tenant Factory

时间:2019-01-22 06:40:13

标签: c# jwt asp.net-core-2.2

我的Web API应用程序中有两个DBContext。第一个是让我所有的客户都使用connestionstring,第二个是真正的应用程序数据库。

登录控件使用MyClientContext,其他所有控制器使用MyContext

我的startup.cs外观

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)

            services.AddDbContext<MyContext>(options =>
                    options.UseNpgsql(Configuration.GetConnectionString("MyContext")));

        services.AddDbContext<MyClientContext>(options =>
                    options.UseNpgsql(Configuration.GetConnectionString("MyClientContext")));
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<MyContext>();
                context.Database.Migrate(); // Code First Migrations for App DB

        var context2 = serviceScope.ServiceProvider.GetRequiredService<MyClientContext>();
                context2.Database.Migrate(); // Code First Migrations for Clients DB
            }

            app.UseCors("AllowSpecificOrigin");
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

成功登录后,我发出看起来像的JWT令牌

private string GenerateJSONWebToken(UserAuth userInfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, userInfo.UserName),
                new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };
            var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], claims,
              expires: DateTime.Now.AddHours(24), signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

在这里,我在启动文件中为真正的DB分配了ConnectionString。我想在用户登录时分配它。如何实现?

1 个答案:

答案 0 :(得分:1)

我已经在代码中进行了以下更改,并且现在可以按预期工作。这可能对其他人有用。

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddDbContext<MyContext>((serviceProvider, options) =>
            {
                var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
                var connection = GetConnection(httpContext);
                options.UseNpgsql(connection);
            });

private string GetConnection(HttpContext httpContext)
        {
            var UserName = httpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
             // Here extract ConnectionString from "MyClientContext"'s DB
        }

对于代码优先数据库迁移,我将Database.Migrate()移到了其类

public MyContext (DbContextOptions<MyContext> options)
            : base(options)
        {
            Database.Migrate();
        }

这对我来说很好。