How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext

前端 未结 3 1362
忘了有多久
忘了有多久 2020-12-28 16:46

How can I access current HttpContext to check for route and parameters inside AuthorizationHandlerContext of Custom Policy-Based Authorization inside ASP.NET Core 2?

相关标签:
3条回答
  • 2020-12-28 17:25

    You should inject an instance of an IHttpContextAccessor into your AuthorizationHandler.

    In the context of your example, this may look like the following:

    public class BadgeEntryHandler : AuthorizationHandler<EnterBuildingRequirement>
    {
        IHttpContextAccessor _httpContextAccessor = null;
    
        public BadgeEntryHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        protected override Task HandleRequirementAsync(
            AuthorizationContext context, 
            EnterBuildingRequirement requirement)
        {
            HttpContext httpContext = _httpContextAccessor.HttpContext; // Access context here
    
            if (context.User.HasClaim(c => c.Type == ClaimTypes.BadgeId &&
                                           c.Issuer == "http://microsoftsecurity"))
            {
                context.Succeed(requirement);
                return Task.FromResult(0);
            }
        }
    }
    

    You may need to register this in your DI setup (if one of your dependencies has not already), as follows:

    services.AddHttpContextAccessor();
    
    0 讨论(0)
  • 2020-12-28 17:34

    You can inject an IHttpContextAccessor into your AuthorizationHandlers constructor.

    e.g.

    public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
    {
        private IHttpContextAccessor _contextAccessor;
    
        public MyAuthorizationHandler (IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
            MinimumPermissionLevelRequirement requirement) {
    
            var httpContext = _contextAccessor.HttpContext;
            // do things
        }
    }
    
    0 讨论(0)
  • 2020-12-28 17:41

    Without injecting, simple solution!

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
            {
                    var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
                    var httpContext = authFilterCtx.HttpContext;  
            }
    
    0 讨论(0)
提交回复
热议问题