Skip to main content

How to Read a Claim from a JsonWebToken in C# with GetPayloadValue

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A JsonWebToken has properties for a few standard claims, such as Subject, but your own claims, such as role, you read by name with GetPayloadValue<T>. It returns the value as the type you ask for, and throws when the claim is missing or has another type. TryGetPayloadValue<T> returns false instead.

Syntax​

Syntax
T value = jwt.GetPayloadValue<T>("<claim>");
bool found = jwt.TryGetPayloadValue<T>("<claim>", out T value);
PartWhat it does
TThe type you want the claim as, such as string or long.
"<claim>"The claim's name in the payload, such as "role".
GetPayloadValue<T>Returns the claim as T. Throws ArgumentException when it can't.
TryGetPayloadValue<T>Returns true and the value when the claim is there and fits T, false otherwise.

Microsoft Learn on GetPayloadValue: it "Gets the 'value' corresponding to key from the JWT payload transformed as type 'T'." It throws an ArgumentException, "Thrown if claim is not found or a transformation to T cannot be made."

The Example​

The example reads a token from another service whose claims are sub, role, iat and exp. It reads role as a string and exp as a long, tries an email claim the token doesn't have with TryGetPayloadValue, and then asks for email with GetPayloadValue.

Prerequisites​

  • .NET SDK. This guide uses .NET SDK 10.0.404.

Step 1: Create the Project​

Terminal
dotnet new console -o demo
cd demo
dotnet package add Microsoft.IdentityModel.JsonWebTokens

dotnet new console creates a console app in a new demo folder, and dotnet package add adds Microsoft.IdentityModel.JsonWebTokens, version 8.23.0 here.

Step 2: Write the Code​

Replace the contents of Program.cs:

Program.cs, which reads a token with ReadJsonWebToken, then writes GetPayloadValue of role as string, exp as long, a TryGetPayloadValue of email with a fallback, and GetPayloadValue of email.

Program.cs
using Microsoft.IdentityModel.JsonWebTokens;

// A token from another service. Its claims are sub, role, iat and exp.
var token = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImtleS0yMDI1LTEyIiwidHlwIjoiSldUIn0.eyJzdWIiOiJhZGEiLCJyb2xlIjoicmVhZGVyIiwiaWF0IjoxNzY0NTQ3MjAwLCJleHAiOjE3NjQ1NTA4MDB9.2EjUXD-_uc78GAdKpsWk7GOlMQztlsdWKQkT-RdKFKE";
var jwt = new JsonWebTokenHandler().ReadJsonWebToken(token);

Console.WriteLine(jwt.GetPayloadValue<string>("role"));
Console.WriteLine(jwt.GetPayloadValue<long>("exp"));
Console.WriteLine(jwt.TryGetPayloadValue<string>("email", out var email) ? email : "no email claim");
Console.WriteLine(jwt.GetPayloadValue<string>("email"));

ReadJsonWebToken reads the token without validating it, which is fine for this example. In an application, read claims from a token you've validated.

Step 3: Run It​

Terminal
dotnet run
Output
reader
1764550800
no email claim
Unhandled exception. System.ArgumentException: IDX14304: Claim with name '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' does not exist in the JsonClaimSet.
at Microsoft.IdentityModel.JsonWebTokens.JsonClaimSet.GetValue[T](String key, Boolean throwEx, Boolean& found)
at Microsoft.IdentityModel.JsonWebTokens.JsonClaimSet.GetValue[T](String key)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.GetPayloadValue[T](String key)
at Program.<Main>$(String[] args) in /Users/Shared/you/demo/Program.cs:line 10

A zsh terminal where dotnet run prints reader, 1764550800 and no email claim, then an unhandled System.ArgumentException IDX14304 saying the claim does not exist in the JsonClaimSet, with its name hidden as PII.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • GetPayloadValue<string>("role") returned reader, and GetPayloadValue<long>("exp") returned the expiry as a number of seconds.
  • TryGetPayloadValue<string>("email", ...) returned false, so the code printed its fallback.
  • GetPayloadValue<string>("email") threw IDX14304 because the claim isn't there. The claim's name appears as [PII of type 'System.String' is hidden ...]: IdentityModel keeps values out of its messages unless you allow it, in case they're personal data.

Common Mistakes​

MistakeWhat happensDo this instead
Calling GetPayloadValue for a claim that may be missingArgumentException: IDX14304: Claim with name ... does not exist in the JsonClaimSet.Use TryGetPayloadValue
Asking for the wrong type, as in GetPayloadValue<int>("role")ArgumentException: IDX14305: Unable to convert the 'role' json property to the following type: 'System.Int32'. Property type was: 'System.String'.Ask for the type the JSON holds
Reading exp as intUnix times fit in int only until 2038Use long, or the ValidTo property

Troubleshooting​

SymptomLikely causeFix
IDX14304The claim isn't in the token, or its name differs in caseCheck the name against the token's payload
IDX14305The claim exists with another JSON typeChange T to match

FAQ​

Why is the claim name hidden in the error?​

IdentityModel hides values it treats as personal data in its exception messages by default. Its message links to https://aka.ms/IdentityModel/PII, which explains the setting.

Is there a property for the standard claims?​

For some: Subject reads sub, Issuer reads iss, and ValidTo reads exp as a DateTime.

Conclusion​

jwt.GetPayloadValue<T>("claim") reads a claim as the type you need and throws when it can't; jwt.TryGetPayloadValue<T>("claim", out var value) returns false instead. Read claims only from a token you've validated when they decide anything.

Additional Resources​