Allow multiple roles to access controller action

前端 未结 9 1244
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:19

Right now I decorate a method like this to allow \"members\" to access my controller action

[Authorize(Roles=\"members\")]

How do I

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 15:38

    Using AspNetCore 2.x, you have to go a little different way:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AuthorizeRoleAttribute : AuthorizeAttribute
    {
        public AuthorizeRoleAttribute(params YourEnum[] roles)
        {
            Policy = string.Join(",", roles.Select(r => r.GetDescription()));
        }
    }
    

    just use it like this:

    [Authorize(YourEnum.Role1, YourEnum.Role2)]
    

提交回复
热议问题