Roles.GetRolesForUser在自定义授权attirbute中不可用

时间:2017-07-25 10:44:13

标签: c# asp.net asp.net-mvc authorization identity

我正在尝试实现自己的自定义属性,我必须为当前用户获取所有角色,如下所示:

public class CustomRoleAuthorization: System.Web.Mvc.AuthorizeAttribute
    {

   public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Login");
                return;
            }
            var requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();

            var userRoles = Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);

            foreach (var item in requiredRoles)
            {
                if (!filterContext.HttpContext.User.IsInRole(item))
                {
                    filterContext.Result = new RedirectResult("~/Index/Index");
                    return;
                }
            }

        }
}

但由于某种原因,这条线不起作用:

 var userRoles = Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);

它说Roles属性是一个字符串,它不包含GetRolesForUser方法?

如何将此扩展方法添加到我的项目中,以便我可以在登录时从身份获取所有用户角色?

@Stephen这是我在登录时设置角色的方式:

 if (user.PasswordHash == PasswordSecurity.CreatePasswordHash(model.Password, user.PasswordSalt))
 {
  ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
 identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.Email));
  List<Claim> claims = new List<Claim>();
 var roles = user.UserRoles.Where(x=>x.Active==true).ToList();
 foreach (var item in roles)
 {
   claims.Add(new Claim(ClaimTypes.Role, item.Roles.RoleName));
  }
 identity.AddClaims(claims);
 identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
 AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddHours(3) }, identity);
 return Json("ok");
 }

1 个答案:

答案 0 :(得分:1)

AuthorizeAttribute包含public string Roles { get; set; }属性(请参阅documentation),因此您需要使用完全限定名称

var userRoles = System.Web.Security.Roles.GetRolesForUser(...

或者您可以为程序集名称

创建别名