How to get the value of a token request and enter dbcontext in the service

I have a DbContext where I need CompanyId to create a global query, for example, for multiple tenants.

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

CompanyId is added to the token application, how can I get the claim value and paste it into 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);
    });
+4
source share
1 answer

You can access the current user through the IHttpContextAccessor service, and then execute the CompanyId request:

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

Note that CompanyId is null. If the user is not authenticated, then CompanyId is null.

: Identity, IHttpContextAccessor. .

+1

Source: https://habr.com/ru/post/1691920/


All Articles