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

前端 未结 1 1205
心在旅途
心在旅途 2021-02-08 05:54

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         


        
相关标签:
1条回答
  • 2021-02-08 06:16

    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>();
    
    0 讨论(0)
提交回复
热议问题