Edit: I implement an AuthorizeFilter
and got the same issue.
I trying to implement permission based authorization like in this post: Permission-Based Authorization in ASP.NET Core multitenant project: A Step-by-Step Guide - DEV Community and Joao Grassi"s blog with custom AuthorizationHandler
and AuthorizationPolicyProvider
. My issue is: after the call to GetPolicyAsync
is executed, it creates a new CurrentTenantService
instance instead of reusing the current one (which has data about current request: conn string, username, etc..). I try to debug but don't know why it do it that way.
Any help is welcome, thank you.
public class PermissionAuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider
{
public PermissionAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
: base(options) { }
/// <inheritdoc />
public override async Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
// ...
return new AuthorizationPolicyBuilder().AddRequirements(requirement).Build();
}
}
I inject 2 services (one will make call to the database, one provide current tenant data) into the AuthorizationHandler
in order to do the authorize logic. So my handler will be register as scoped.
public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
private readonly ICurrentTenantService _currentTenantService;
private readonly ISecurityService _securityService;
public PermissionHandler(ICurrentTenantService currentTenantService, ISecurityService securityService)
{
_currentTenantService = currentTenantService;
_securityService = securityService;
}
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context, PermissionRequirement requirement)
{
// Authorizing.....
}
}
and they are registered like this:
builder.Services.AddScoped<ICurrentTenantService, CurrentTenantService>(); // contain connStr
builder.Services.AddDbContext<SecurityDbContext>();
builder.Services.AddDbContext<SystemDataDbContext>();
// Register custom Authorization handler
builder.Services.AddScoped<IAuthorizationHandler, PermissionHandler>();
// Overrides the DefaultAuthorizationPolicyProvider
builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
// Middlewares
app.UseMiddleware<AuthenticationMiddleware>();
app.UseAuthorize();
I did try debugging step by step to find what cause the CurrentTenantService
to reinitialize.
I try to register my handler as singleton and get those dependencies through IServiceProvider
, but this yields the same result.