【问题标题】:JWT: How to get a List of Values from a specific Key in the Claims. C# Asp.Net CoreJWT:如何从声明中的特定键获取值列表。 C# Asp.Net 核心
【发布时间】:2021-04-18 17:29:01
【问题描述】:

我正在使用这段代码从 JWT 中的声明中读取单个值。

return httpContext.User.Claims.Single(x => x.Type == "id").Value;

获取此声明的价值:

"id": "b6dddcaa-dba6-49cf-ae2d-7e3a5d060553"

但是,我想读取具有多个值的键。 但使用相同的代码:

return httpContext.User.Claims.Single(x => x.Type == "groups").Value;

对于此声明:

  "groups": [
    "123",
    "234"
  ],

我从逻辑上得到以下错误消息:

System.InvalidOperationException: "Sequence contains more than one matching element"

找不到对应的方法。有人可以帮我吗?

【问题讨论】:

    标签: c# asp.net asp.net-core jwt claims


    【解决方案1】:

    因为Single(),用Where()代替Single()

    return httpContext.User.Claims
              .Where(x => x.Type == "groups")  //Filter based on condition
              .Select(y => y.Value);  // get only Value 
    

    Single():它返回一个序列的单个特定元素。 如果找到多个满足条件的元素会抛出错误

    【讨论】:

      【解决方案2】:

      参考ClaimsPrincipal.FindAll(Predicate<Claim>)

      检索与指定谓词匹配的所有声明。

      IEnumerable<Claim> claims = httpContext.User.FindAll(x => x.Type == "groups");
      IEnumerable<string> values = claims.Select(c => c.Value);
      return values;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 2011-11-14
        • 2018-06-16
        • 1970-01-01
        • 2019-06-17
        • 2015-09-17
        • 1970-01-01
        相关资源
        最近更新 更多