skip to Main Content

I have a role controller with Auth

 [Authorize(Roles = Roles.Visitor, AuthenticationSchemes = AuthorizationSchemes.Visitor)]

I need to add another policy AdminPolicy to it but it should work for either of them. Is there a simple way to do that?

My admin policy has a requirement handler

options.AddPolicy(Policies.Admin,
                policy => policy.Requirements
                    .Add(new AdminRequirement()));

And the handler looks like this

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AdminRequirement requirement)
    {
        if (context.HasSucceeded || context.HasFailed) {
            return;
        }

        if (context.User.HasClaim(c => c.Type.Equals("administration"))
            && context.User.HasClaim(c => c.Type.Equals("admin"))) {
            context.Succeed(requirement);
        }

    }

3

Answers


  1. I hope you are looking multiple role authentication,

    [Authorize(Roles = "Administrator, Vistor")]
    public class WeatherController : Controller {
        
    }
    

    For more info please link look into documentation

    Login or Signup to reply.
  2. I need to add another policy AdminPolicy to it but it should work for
    either of them

    As far as I know, using both roles and declaring roles in the policy via the attribute method is not feasible. Now we can only create a new policy, which contains administration && admin(the same as AdminPolicy ), and then use ‘or’ to join Roles.Visitor.

    In the controller, you only need to use this new Policy without adding Roles and AdminPolicy.

    Login or Signup to reply.
  3. I used something like below, where I needed to combine multiple roles into a single policy.

    services.AddAuthorization(options =>
    {
        options.AddPolicy("GeneralAdmin", policy =>
            policy.RequireAssertion(context =>
                context.User.HasClaim(ClaimTypes.Role, "AdminOfX") ||
                context.User.HasClaim(ClaimTypes.Role, "AdminOfY")));
    }
    

    And then use it:

    [Authorize(Policy = "GeneralAdmin")] 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search