如何写AuthorizeAttribute如果一个角色包含空间(How to write Autho

2019-06-25 08:50发布

我使用MVC3 / 4。 但它只是在授权一个一般性的问题。

一个数据库中的我已经被命名为“旅行领袖”的角色,其中包含了空间。

我试过[Authorize(Roles="'Trip Leader', Administrator")]但未能奏效。 任何人都可以帮忙吗?

Answer 1:

创建自己的属性,并从AuthorizeAttribute派生。 然后重写AuthorizeCore方法和实施对包含空格的作用,你自己有验证逻辑。

一个例子可能是这样的:

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));
   }

}

用法

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


Answer 2:

试试这个:

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

编辑:上面的代码需要用户来满足这两个角色。 如果你正在寻找一个非此即彼/或授权,试试这个:

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


Answer 3:

我不能让其他答案工作。 我的角色,曾在他们的逗号,也不会与原来的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));
        }
    }


文章来源: How to write AuthorizeAttribute if a role contains space