Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access dbcontext & session in Custom Policy-Based Authorization

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();

    }
}
like image 868
WolfPack Avatar asked Sep 20 '16 09:09

WolfPack


1 Answers

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>();
like image 138
blowdart Avatar answered Sep 24 '22 08:09

blowdart