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
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }
ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.
Role-Based Authorization in ASP.NET Core You can specify what roles are authorized to access a specific resource by using the [Authorize] attribute. You can even declare them in such a way that the authorization evaluates at the controller level, action level, or even at a global level. Let's take Slack as an example.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With