Allow multiple roles to access controller action

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

    Better code with adding a subclass AuthorizeRole.cs

        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
        class AuthorizeRoleAttribute : AuthorizeAttribute
        {
            public AuthorizeRoleAttribute(params Rolenames[] roles)
            {
                this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
            }
            protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
            {
                if (filterContext.HttpContext.Request.IsAuthenticated)
                {
                    filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                      { "action", "Unauthorized" },
                      { "controller", "Home" },
                      { "area", "" }
                      }
                  );
                    //base.HandleUnauthorizedRequest(filterContext);
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                      { "action", "Login" },
                      { "controller", "Account" },
                      { "area", "" },
                      { "returnUrl", HttpContext.Current.Request.Url }
                      }
                  );
                }
            }
        }
    

    How to use this

    [AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
    
    public ActionResult Index()
    {
    return View();
    }
    

提交回复
热议问题