How to write AuthorizeAttribute if a role contains space

六月ゝ 毕业季﹏ 提交于 2019-11-30 20:47:17

Create your own attribute and derive from AuthorizeAttribute. Then override the AuthorizeCore method and implement your own logic with validation on a role that contains a space.

An example could be something like this:

public class CustomAuthAttribute : AuthorizeAttribute
{
   private readonly IUserRoleService _userRoleService;
   private string[] _allowedRoles;

   public CustomAuthAttribute(params string[] roles)
   {
      _userRoleService = new UserRoleService();
      _allowedRoles = roles;
   }
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
    //something like this.
    var userName = httpContext.User.Identity.Name;
    var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings
    return _allowedRoles.Any(x => userRoles.Contains(x));
   }

}

Usage

[CustomAuth("role withspace","admin")]
public ActionResult Index()
{
}

Try this:

[Authorize(Roles="Trip Leader")]
[Authorize(Roles="Administrator")]

EDIT: The above code requires the user to fulfill both roles. If you are looking for an either/or authorization, try this:

[Authorize(Roles="Trip Leader, Administrator")]

I could not get the other answers to work. My roles had commas in them and wouldn't work with the original AuthorizeAttribute.

   //Custom Authorize class that derives from the existing AuthorizeAttribute
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {

        private string[] _allowedRoles;

        public CustomAuthorizeAttribute(params string[] roles)
        {
            //allowed roles
            _allowedRoles = roles;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var roleManager = httpContext.GetOwinContext().Get<ApplicationUserManager>();
            //Grab all of the Roles for the current user
            var roles = roleManager.GetRoles(httpContext.User.Identity.GetUserId());
            //Determine if they are currently in any of the required roles (and allow / disallow accordingly) 
            return _allowedRoles.Any(x => roles.Contains(x));
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!