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

Hrvoje Kusulja picture Hrvoje Kusulja · Dec 14, 2017 · Viewed 11.7k times · Source

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

Ref example: Custom Policy-Based Authorization

Answer

PepR picture PepR · Dec 14, 2017

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