Authorize Attribute with Multiple Roles

前端 未结 5 1293
长发绾君心
长发绾君心 2020-12-02 07:00

I would like to add Authorization to a controller, for multiple Roles at once.

Normally that would look like this:

[Authorize(Roles = \"RoleA,RoleB,R         


        
5条回答
  •  伪装坚强ぢ
    2020-12-02 07:02

    I feel like a custom authorize attribute is overkill for this issue unless you have a large amount of roles.

    Since the string must be known at compile time, why not make a static Role class that contains public strings of the roles you have defined, and then add comma separated strings with certain roles that you want to authorize:

    public static class Roles
    {
        public const string ADMIN = "Admin";
        public const string VIEWER = "Viewer";
    
        public const string ADMIN_OR_VIEWER = ADMIN + "," + VIEWER;
    }
    

    And then you can use the Authorize Attribute like so on the Controller Class or the Controller Method (or both):

    [Authorize(Roles = Roles.ADMIN]
    public class ExampleController : Controller
    {
        [Authorize(Roles = Roles.ADMIN_OR_VIEWER)
        public ActionResult Create()
        {
            ..code here...
        }
    }
    

提交回复
热议问题