Search code examples
c#asp.netasp.net-corejwtclaims

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


I am using this piece of code to read a single value from the claims in the JWT.

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

to get the value of this claim:

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

However, I want to read a key that has multiple values. But with the same code:

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

for this claim:

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

I logically get the following error message:

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

I can't find the corresponding method. Can someone help me?


Solution

  • It is because of Single(), use Where() instead of Single()

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

    Single(): It returns a single, specific element of a sequence. It throws an error if there are multiple elements found which satisfies the condition