如果角色包含空格,如何编写授权属性

本文关键字:何编写 授权 属性 角色 包含 空格 如果 | 更新日期: 2023-09-27 18:36:40

我正在使用MVC3/4。但这只是授权中的一般问题。

我拥有的角色之一是数据库中的"旅行领导者",其中包含一个空格。

我尝试了[Authorize(Roles="'Trip Leader', Administrator")]但它不起作用。谁能帮忙?

如果角色包含空格,如何编写授权属性

创建自己的属性并从 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()
{
}

试试这个:

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

编辑:上面的代码要求用户履行这两个角色。如果您正在寻找非此即彼的授权,请尝试以下操作:

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

我无法获得其他答案。我的角色中有逗号,不能与原始的授权属性一起使用。

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