1

我正在使用 ASP NET MVC 5 和 Owin 进行身份验证。在我的帐户控制器中,我像这样设置用户:

  var claims = new List<Claim>();
  claims.AddRange(new List<Claim>
                                {
                                    new Claim(ClaimTypes.Name, "john"),                                    
                                    new Claim(ClaimTypes.Sid, "123"),
                                    (...)
                                });
  var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
  id.AddClaim(new Claim(ClaimTypes.Role, selUser.Role));
  authenticationManager.SignIn(new AuthenticationProperties
                             {
                                IsPersistent = false
                              }, id);

显然,我将(单一)角色添加到身份中。在随后的请求中,当我呈现具有角色特定内容的视图时,我的自定义角色提供程序类的 GetRolesForUser(string username) 被调用。我要做的就是从授权用户解包角色声明并返回这些角色的列表。但是,当迭代 Claims IEnumerable 时,在所有声明都被迭代之后,GetRolesForUser 会再次被调用,我最终会陷入一个永无止境的递归调用循环。

只有一个角色,我通过在找到第一个角色类型声明后立即从函数返回来创建一种解决方法:

public override string[] GetRolesForUser(string username) {
            var id = ClaimsPrincipal.Current.Identities.First();
            foreach (Claim c in id.Claims)
            {                
                if (c.Type == ClaimTypes.Role) return new string[] { c.Value };
            }

然而,这样的事情永远不会结束:

string role = id.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).SingleOrDefault();

为什么?遍历声明调用 GetRolesForUser?如果我有多个角色场景,我将如何获得所有角色的数组?

谢谢,

伊戈尔

4

1 回答 1

-1

尝试这个

var id = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
var roles = id.FindAll(x => x.Type == ClaimTypes.Role).Select(x=> x.Value).ToArray();
于 2014-04-07T13:04:09.343 回答