[英]How to convert List<Claim> to Dictionary<string,object>?
I'm getting my claims to put on jwt token我正在申请使用 jwt 令牌
Get Valid Claims and Generate Jwt Token获取有效声明并生成 Jwt 令牌
var claims = await GetValidClaims(users);
Token = GenerateJwtToken(users, claims);
GenerateJwtToken Method生成JwtToken方法
private string GenerateJwtToken(ApplicationUser user, List<Claim> claims)
{
var dicClaim = new Dictionary<string,object>();
...
var tokenDescriptor = new SecurityTokenDescriptor
{
Claims = dicClaim, // <<<<<<<<<< this Claims is Dictionary<string,object>
...
}
}
GetValidClaims Method GetValidClaims 方法
private async Task<List<Claim>> GetValidClaims(ApplicationUser user)
{
IdentityOptions _options = new IdentityOptions();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(_options.ClaimsIdentity.UserIdClaimType, user.Id.ToString()),
new Claim(_options.ClaimsIdentity.UserNameClaimType, user.UserName)
};
var userClaims = await _userManager.GetClaimsAsync(user);
var userRoles = await _userManager.GetRolesAsync(user);
claims.AddRange(userClaims);
foreach (var userRole in userRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
var role = await _roleManager.FindByNameAsync(userRole);
if (role != null)
{
var roleClaims = await _roleManager.GetClaimsAsync(role);
foreach (Claim roleClaim in roleClaims)
{
claims.Add(roleClaim);
}
}
}
return claims;
}
At this line: Claims = dicClaim, // <<<<<<<<<< this Claims is Dictionary<string,object>
在这一行: Claims = dicClaim, // <<<<<<<<<< this Claims is Dictionary<string,object>
But I don't know how to convert List to Dictionary但我不知道如何将列表转换为字典
I already tried something like this:我已经尝试过这样的事情:
claims.ToDictionary(x=>x,x=>x.Value)
claims.ToDictionary(x=>x.Value,x=>x)
In order to create a dictionary we have to define a unique Key
for it.为了创建字典,我们必须为它定义一个唯一的Key
。 Assuming that假如说
Type
or at least start from Type
我们希望我们的关键是说Type
或至少从Type
开始we can solve it like this:我们可以这样解决:
Group
all claims by Type
(desired key)按Type
(所需键)对所有声明进行Group
1
claim in a group, use Value
as Key
如果组中只有1
声明,请使用Value
作为Key
Type_1
, Type_2
, ..., Type_N
Key
s如果没有,让我们生成Type_1
, Type_2
, ..., Type_N
Key
sCode代码
var dicClaim = claims
.GroupBy(claim => claim.Type) // Desired Key
.SelectMany(group => group
.Select((item, index) => group.Count() <= 1
? Tuple.Create(group.Key, item) // One claim in group
: Tuple.Create($"{group.Key}_{index + 1}", item) // Many claims
))
.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
If in case of repeated claims you want to get, say, the Last
one only, you can do it with the code:如果在重复声明的情况下,您只想获得Last
一个声明,则可以使用以下代码:
var dicClaim = claims
.GroupBy(claim => claim.Type) // Desired Key
.ToDictionary(group => group.Key, group => group.Last());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.