6

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

我的角色之一在数据库中被命名为“Trip Leader”,其中包含一个空格。

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

4

3 回答 3

3

创建您自己的属性并从 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()
{
}
于 2012-10-25T07:05:05.250 回答
0

试试这个:

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

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

[Authorize(Roles="Trip Leader, Administrator")]
于 2012-06-08T20:30:02.903 回答
0

我无法得到其他答案。我的角色中有逗号,不能与原始 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));
        }
    }
于 2018-06-01T06:02:32.030 回答