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?
services.AddAuthorization(options =>
{
options.AddPolicy("CheckAuthorize",
policy => policy.Requirements.Add(new CheckAuthorize()));
});
services.AddSingleton<IAuthorizationHandler, CheckAuthorize>();
public class CheckAuthorize : AuthorizationHandler<CheckAuthorize>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CheckAuthorize requirement)
{
if () //check session to verify user is logged in or not
{
//redirect to login page
}
else
{
if ()//access dbcontext get data from database table to validate user access
{
//redirect to access denied page
}
}
throw new NotImplementedException();
}
}
Policies can use DI
So, assuming your db context is in DI you could do something like
public class CheckAuthorizeHandler : AuthorizationHandler<CheckAuthorizeRequirement>
{
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<CheckAuthorize>, IAuthorizationRequirement
, so you'd have to do
public CheckAuthorizeRequirement : IAuthorizationRequirement
{
}
And finally you need to register your handler in the DI system
services.AddTransient<IAuthorizationHandler, CheckAuthorizeHandler>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With