1

I'm looking for recommendations on how to have multiple authorize attributes on an action.

eg:

[AuthorizePermission(PermissionName.SectionOne, PermissionLevel.Two)]
[AuthorizePermission(PermissionName.SectionTwo, PermissionLevel.Three)]
public ActionResult Index(int userId = 0){

}

If the user has access to SectionOne OR SectionTwo with the required PermissionLevel then they should be allowed in.

The problem i'm facing is how do I check both attributes before deciding they aren't allowed in (as they are separate attributes)? If the first one fails then it will never get to the second one.

I can not pass both permission sets to one attribute as they need to be paired together.

Does anyone have any suggestions?

Andrew
  • 611
  • 6
  • 14

2 Answers2

2

I can not pass both permission sets to one attribute as they need to be paired together.

Yes, you can.

There is no reason why you can't include all the permissions in a single attribute. Something like this:

[AuthorizePermission(new Permission[]{
   new Permission(PermissionName.SectionOne, PermissionLevel.Two), 
   new Permission(PermissionName.SectionTwo, PermissionLevel.Three)}]

This would pass an array of Permission objects, which you can then evaluate in your method with OR logic.

public class AuthorizePermissionAttribute : AuthorizeAttribute
{
    private Permission[] _permissions = null;
    public AuthorizePermissionAttribute(Permission[] permissions)
    {
        _permissions = permissions;
    }
}

You could even get fancy and add a parameter that tells whether to AND or OR them...

Erik Funkenbusch
  • 90,480
  • 27
  • 178
  • 274
0

The only way that I know is something like this

 public class CustomRolesAttribute : AuthorizeAttribute
  {
     public CustomRolesAttribute(params string[] roles)
     {
       Roles = String.Join(",", roles);
     }
  }

Usage:

[CustomRoles("members", "admin")]
Ignacio Laborde
  • 1,342
  • 2
  • 10
  • 10