【问题标题】:How to convert List<Claim> to Dictionary<string,object>?如何将 List<Claim> 转换为 Dictionary<string,object>?
【发布时间】:2019-07-29 14:36:12
【问题描述】:

我正在申请使用 jwt 令牌

获取有效声明并生成 Jwt 令牌

var claims = await GetValidClaims(users);
Token = GenerateJwtToken(users, claims);

生成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 方法

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;
}

在这一行:Claims = dicClaim, // &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this Claims is Dictionary&lt;string,object&gt;

但我不知道如何将列表转换为字典

我已经尝试过这样的事情:

claims.ToDictionary(x=&gt;x,x=&gt;x.Value)

claims.ToDictionary(x=&gt;x.Value,x=&gt;x)

库SecurityTokenDescriptor

【问题讨论】:

  • 请注意,声明可以重复。所以它可能不是字典的唯一键
  • 我不知道该怎么做:/
  • SecurityTokenDescriptor 对象使用什么库? official docs 没有提到 Caims 属性,因为 .net 框架 4.5...我无法弄清楚你对这段代码的意图是什么
  • @DiegoRafaelSouza Microsoft.IdentityModel.Tokens
  • 你知道怎么做一个foreach循环吧?只需像这样创建一个字典, var myDictionary = new Dictionary() 然后遍历声明并调用 myDictionary.Add(claim.ClaimType, claim.ClaimValue)。如前所述,索赔可以重复,这意味着您可以拥有无​​数具有相同索赔类型的索赔,因此字典可能不是您的最佳选择。你需要这个做什么?

标签: c# list dictionary


【解决方案1】:

为了创建一个字典,我们必须为它定义一个唯一Key。假设

  1. 我们希望我们的密钥成为例如Type 或至少从Type 开始
  2. 索赔可以重复

我们可以这样解决:

  1. GroupType 的所有声明(所需密钥)
  2. 如果组中只有1 声明,请使用Value 作为Key
  3. 如果没有,让我们生成Type_1,Type_2,...,Type_NKeys

代码

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); 

如果重复声明您只想获得Last 一个,您可以使用代码:

 var dicClaim = claims
   .GroupBy(claim => claim.Type) // Desired Key
   .ToDictionary(group => group.Key, group => group.Last());

【讨论】:

  • 在这行,group.value 不包含值的定义
  • 如果我删除 .Value 它可以工作,但我得到另一个错误:无法隐式转换类型 '...Dictionary>' 到 '...IDictionary'
  • @LeoHenrique:很抱歉我的错字,应该是item
  • 这应该是.GroupBy(claim => claim.Type).,否则这是正确的
猜你喜欢
  • 2017-09-20
  • 1970-01-01
  • 2014-10-22
  • 2014-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多