How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext
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();
You can inject an IHttpContextAccessor
into your AuthorizationHandler
s 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
}
}