.net - 无法从 GenericIdentity 检索角色

标签 .net asp.net-identity .net-security

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

我错过了什么?

Example: 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");

最佳答案

在您的代码中,您将角色添加到 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);
}

Example: 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);
}

关于.net - 无法从 GenericIdentity 检索角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834490/

相关文章:

c# - AspNetUserLogins 表标识

javascript - 有人可以解释一下这个 Facebook 脚本吗? XSS?

c# - 如何处理 System.IndexOutOfRangeException

c# - XML架构

asp.net-identity - 如何向IdentityServer DI框架注册ApplicationUserManager?

c# - Intranet 站点的 ASP.NET Identity + Windows 身份验证

asp.net - 在 aspnetdb 表中添加列好吗?

c# - 使用 javascript 创建 .net md5

c# - 如何在 .Net 中实现 "convert using this function"自定义属性?

c# - azure worker roleOutput类型为Class Library的项目无法直接启动