繁体   English   中英

JWT:如何从声明中的特定键获取值列表。 C# 网络核心

[英]JWT: How to get a List of Values from a specific Key in the Claims. C# Asp.Net Core

我正在使用这段代码从 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"

我找不到相应的方法。 有人能帮我吗?

这是因为Single() ,使用Where()而不是Single()

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

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

参考ClaimsPrincipal.FindAll(Predicate<Claim>)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM