无法从 GenericIdentity 检索角色

Sri*_*eti 2 .net .net-security asp.net-identity

我正在设置一个GenericPrincipal添加GenericIdentity& 角色,但是当我尝试从中检索角色时,我什么也没得到。但是,如果我调用Principal.IsInRole,它会返回正确的值。

我错过了什么?

示例: https : //dotnetfiddle.net/Uan3ru

var identity = new GenericIdentity("Test", "Test");
var pricipal = new GenericPrincipal(identity, new[] { "Role1", "Role2" });
var cls = identity.Claims
                  .Where(c => c.Type == ClaimTypes.Role)
                  .Select(c => c.Value);
foreach(var c in cls)
{
    Console.WriteLine(c);
}
Console.WriteLine("complete");
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 5

在您的代码中,您将角色添加到GenericPrincipal对象,而不是GenericIdentity对象。

因此,身份对象没有任何关联的角色声明,而主体对象有。


从中获取角色 GenericPrincipal

您应该能够GenericPrincipal像这样从对象中获取角色:

var identity = new GenericIdentity("Test", "Test");
var principal = new GenericPrincipal(identity, new[] { "Role1", "Role2" });

// We need to get the claims associated with the Principal instead of the Identity
var roles = principal.Claims
                     .Where(c => c.Type == ClaimTypes.Role)
                     .Select(c => c.Value);

Console.WriteLine("Roles associated with the GenericPrincipal:");
foreach(var role in roles)
{
    Console.WriteLine(role);
}
Run Code Online (Sandbox Code Playgroud)

示例: https : //dotnetfiddle.net/wCxmIR


从中获取角色 GenericIdentity

如果您需要跟踪特定GenericIdentity对象的角色,则必须将角色声明显式添加到实例中。然后,您可以像这样从身份对象中获取角色:

var roles = new[] { "Role1", "Role2" };
var identity = new GenericIdentity("Test", "Test");

// Explicitly add role Claims to the GenericIdentity
foreach (var role in roles)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, role));
}

Console.WriteLine(String.Empty);
Console.WriteLine("All Claims associated with the GenericIdentity:");
foreach (var claim in identity.Claims)
{
    Console.WriteLine(claim);
}
Run Code Online (Sandbox Code Playgroud)