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