2

In my asp.net-core application I use policies (e.g. "IsAdmin") to secure certain parts of the application.

I have an admin area located at the path /admin. I would like require a policy for every controller/page located under this path instead of decorating every controller with the [Autorization] attribute.

Is there a way to set this up in startup.cs?

1 Answer 1

3

AFAIK , no such configuration enable path filter for policy . As a workaround , you can create a base controller definition for that area that overrides Controller, and add the security require to this:

[Authorize(Policy = "RequireElevatedRights")]
public abstract class AdminController : Controller { }

Then you just have to ensure each controller in the area overrides AdminController instead of Controller:

[Area("Admin")]
public class HomeController : AdminController
{
    public IActionResult Index()
    {
        return View();
    }
}

Another solution is applying a global authorization requirement :

services.AddMvc(config =>
{

    config.Filters.Add(new AuthorizeFilter("AtLeast21"));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddAuthorization(options =>
{

    options.AddPolicy("AtLeast21", policy =>
policy.Requirements.Add(new MinimumAgeRequirement(21)));
});

services.AddHttpContextAccessor();
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();

In handle you should check whether the area is the specfic one :

IHttpContextAccessor _httpContextAccessor = null;

public MinimumAgeHandler(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,                                                       MinimumAgeRequirement requirement)
{
    var mvcContext = context.Resource as AuthorizationFilterContext;
    var descriptor = mvcContext?.ActionDescriptor as ControllerActionDescriptor;
    if (!("Admin".Equals(descriptor.RouteValues["area"])))
    {
        context.Succeed(requirement);
    }
    ...........
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The key to my problem was solved by these lines: services.AddMvc(config => { config.Filters.Add(new AuthorizeFilter("AtLeast21")); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); In the RequirementsHandler I can now check the request path and fullfill the requirement based on user and path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.