Home > other >  Use either Policy based or Role based Authorization for an endpoint in .Net
Use either Policy based or Role based Authorization for an endpoint in .Net

Time:03-21

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);
        }

    }

CodePudding user response:

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.

CodePudding user response:

I hope you are looking multiple role authentication,

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

For more info please link look into documentation

  • Related