Allow multiple roles to access controller action

前端 未结 9 1245
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    For MVC4, using a Enum (UserRoles) with my roles, I use a custom AuthorizeAttribute.

    On my controlled action, I do:

    [CustomAuthorize(UserRoles.Admin, UserRoles.User)]
    public ActionResult ChangePassword()
    {
        return View();
    }
    

    And I use a custom AuthorizeAttribute like that:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class CustomAuthorize : AuthorizeAttribute
    {
        private string[] UserProfilesRequired { get; set; }
    
        public CustomAuthorize(params object[] userProfilesRequired)
        {
            if (userProfilesRequired.Any(p => p.GetType().BaseType != typeof(Enum)))
                throw new ArgumentException("userProfilesRequired");
    
            this.UserProfilesRequired = userProfilesRequired.Select(p => Enum.GetName(p.GetType(), p)).ToArray();
        }
    
        public override void OnAuthorization(AuthorizationContext context)
        {
            bool authorized = false;
    
            foreach (var role in this.UserProfilesRequired)
                if (HttpContext.Current.User.IsInRole(role))
                {
                    authorized = true;
                    break;
                }
    
            if (!authorized)
            {
                var url = new UrlHelper(context.RequestContext);
                var logonUrl = url.Action("Http", "Error", new { Id = 401, Area = "" });
                context.Result = new RedirectResult(logonUrl);
    
                return;
            }
        }
    }
    

    This is part of modifed FNHMVC by Fabricio Martínez Tamayo https://github.com/fabriciomrtnz/FNHMVC/

提交回复
热议问题