Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 564
Hrvoje Kusulja Avatar asked Dec 14 '17 09:12

Hrvoje Kusulja


People also ask

How do I find HttpContext current?

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... }

How use HttpContext current in .NET Core?

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.

How would you apply an authorization policy to a controller in an ASP.NET Core application?

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.


1 Answers

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(); 
like image 194
SpruceMoose Avatar answered Oct 01 '22 16:10

SpruceMoose