How to create a custom authorization attribute to validate a role and URL in Asp.Net Core?

I want to create a custom authorization attribute to verify the path and URL.

I found a way to do this in Asp.Net Core using an authorization-based policy, but I tried to implement it, but I cannot get the HttpContext with the incoming URL.

AuthorizationHandlerContext does not have access to HttpContext.

How can I get the current HttpContext with a url? Can this be done, or using another method?

I tried this code to create a custom policy:

public class RoleUrlValidationHandler : AuthorizationHandler<RoleUrlValidationRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleUrlValidationRequirement requirement)
    {           
        var path = //Here I need get current url path for example - /api/posts/4545411
        var pathPart = path.Split('/');
        var clientId = pathPart[3];

        if (context.User.IsInRole(clientId))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

I want to create the following:

[Authorize(Policy="RoleUrlValidation")] //Get ClientId from Url and check User roles
public class PostsController : Controller
{
    public ActionResult Get()
    {
    }
}
+4
source share
1 answer

. , , , Injection Dependency .

public class RoleUrlValidationHandler : AuthorizationHandler<RoleUrlValidationRequirement>
{
    private readonly IHttpContextAccessor contextAccessor;
    public class RoleUrlValidationHandler(IHttpContextAccessor contextAccessor)
    {
        this.contextAccessor = contextAccessor;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleUrlValidationRequirement requirement)
    {
        var httpContext = contextAccessor.HttpContext;
        var path = httpContext.Request.Path;
        var pathPart = path.Split('/');
        var clientId = pathPart[3];

        if (context.User.IsInRole(clientId))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

IHttpContextAccessor, .

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

:

var routeData = httpContext.GetRouteData() path.Split('/') , .

+6

Source: https://habr.com/ru/post/1666149/


All Articles