简体   繁体   English

如何转换列表<Claim>到字典<string,object> ?

[英]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)

Lib SecurityTokenDescriptor Lib SecurityTokenDescriptor 在此处输入图片说明

In order to create a dictionary we have to define a unique Key for it.为了创建字典,我们必须为它定义一个唯一的Key Assuming that假如说

  1. We want our key to be say, Type or at least start from Type我们希望我们的关键Type或至少从Type开始
  2. Claims can be repeated索赔可以重复

we can solve it like this:我们可以这样解决:

  1. Group all claims by Type (desired key)Type (所需键)对所有声明进行Group
  2. If there's only 1 claim in a group, use Value as Key如果组中只有1声明,请使用Value作为Key
  3. If not, let's generate Type_1 , Type_2 , ..., Type_N Key s如果没有,让我们生成Type_1 , Type_2 , ..., Type_N Key s

Code代码

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.

相关问题 如何转换字典 <string, object> 列出 <T> - How to convert Dictionary<string, object> to List<T> 如何转换字典 <string, List<object> &gt;进入C#中的DataTable? - How to convert Dictionary<string, List<object>> into DataTable in C#? 如何将数据表转换为字典 <string, list<object> &gt;在C#中? - How to convert a datatable to dictionary<string, list<object>> in C#? 如何将字符串转换为字典列表 - How to convert string to list of dictionary '将'Dictionary <string,int>转换为List <object> - 'Convert' Dictionary<string,int> into List<object> C#转换字典 <string, List<> &gt;到字典 <string, object> - c# Convert Dictionary<string, List<>> to Dictionary<string, object> 如何转换List <String> 到字典 <int,String> - How to convert List<String> to Dictionary<int,String> 如何转换字典 <string, object> 到字典 <string, string> 在C#中 - How to convert Dictionary<string, object> to Dictionary<string, string> in c# 如何转换列表 <Dictionary<string, object> &gt;到列表 <string> 在lambda中每个项目的“名称”属性是什么? - How convert a List<Dictionary<string, object>> to a List<string> of each item's “name” property in a lambda? 如何转换字典 <object, string> 到字典 <object, List<string> &gt;使用LINQ - How to transform a Dictionary<object, string> to a Dictionary<object, List<string>> with LINQ
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM