Is it possible that we can access dbcontext to get my table data and session in custom Policy-Based Authorization? Anyone can help how to achieve it?
ser
Policies can use DI
So, assuming your db context is in DI you could do something like
public class CheckAuthorizeHandler : AuthorizationHandler
{
MyContext _context;
public CheckAuthorizeHandler(MyContext context)
{
_context = context;
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
MyRequirement requirement)
{
// Do something with _context
// Check if the requirement is fulfilled.
return Task.CompletedTask;
}
}
Note that when you do this you have to make your requirement a seperate class, you can't do CheckAuthorize : AuthorizationHandler
, so you'd have to do
public CheckAuthorizeRequirement : IAuthorizationRequirement
{
}
And finally you need to register your handler in the DI system
services.AddTransient();