Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc decorate [Authorize()] with multiple enums

I have a controller and I want two roles to be able to access it. 1-admin OR 2-moderator

I know you can do [Authorize(Roles="admin, moderators")] but I have my roles in an enum. With the enum I can only authorize ONE role. I can't figure out how to authorize two.

I have tried something like [Authorize(Roles=MyEnum.Admin, MyEnum.Moderator)] but that wont compile.

Someone once suggested this:

 [Authorize(Roles=MyEnum.Admin)]  [Authorize(MyEnum.Moderator)]  public ActionResult myAction()  {  } 

but it doesn't work as an OR. I think in this case the user has to be part of BOTH roles. Am I overlooking some syntax? Or is this a case where I have to roll my own custom authorization?

like image 496
codette Avatar asked Jul 18 '09 19:07

codette


1 Answers

Here is a simple and elegant solution which allows you to simply use the following syntax:

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)] 

When creating your own attribute, use the params keyword in your constructor:

public class AuthorizeRoles : AuthorizeAttribute {     public AuthorizeRoles(params MyEnum[] roles)     {         ...     }     protected override bool AuthorizeCore(HttpContextBase httpContext)     {         ...     } } 

This will allow you to use the attribute as follows:

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)] public ActionResult myAction() { } 
like image 185
Zaid Masud Avatar answered Sep 19 '22 18:09

Zaid Masud