gpt4 book ai didi

.net - 无法从 GenericIdentity 检索角色

转载 作者:行者123 更新时间:2023-12-02 17:33:34 25 4
gpt4 key购买 nike

我正在设置一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com