如何获取令牌声明值并在数据库上下文服务上注入



我有一个 DbContext,我需要 CompanyId 来进行全局查询,比如多租户。

    public void SetGlobalQuery<T>(ModelBuilder builder) where T : BaseEntity
    {
        builder.Entity<T>().HasQueryFilter(e => e.CompanyId == _companyId);
    }

公司 ID 被添加到令牌声明中,我如何获取声明值并在 DbContext 上注入?

    services.AddScoped(provider => {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        var options = optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MyDbDatabase")).Options;
        var companyId = 1;
        return new DocContext(options, companyId);
    });

您可以通过 IHttpContextAccessor 服务访问当前用户,然后搜索 CompanyId 声明:

//using System.Security.Claims;
services.AddScoped(provider => {
    var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
    var options = optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MyDbDatabase")).Options;
    var user = provider.GetRequiredService<IHttpContextAccessor>().HttpContext.User;
    int? companyId = int.TryParse(user.FindFirstValue("CompanyId"), out var companyId) ? companyId : (int?)null;
    return new DocContext(options, companyId);
});

请注意,公司 ID 是一个可为空的整数。如果用户未通过身份验证,则公司 ID 为空。

旁注:如果您使用的是 Identity,则会为您注入 IHttpContextAccessor。否则,您将不得不自己做。

最新更新