Skip to main content

How to Add Custom Claims to a JWT in .NET C# with SecurityTokenDescriptor.Claims

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

SecurityTokenDescriptor.Claims is a Dictionary<string, object>, and each entry in it becomes a claim in the JWT that JsonWebTokenHandler creates. A value can be text, a number, an array or another dictionary, which becomes a JSON object.

Syntax​

Syntax
var token = new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
Claims = new Dictionary<string, object>
{
["<name>"] = <value>,
},
SigningCredentials = <credentials>,
});
PartWhat it does
ClaimsThe claims to write into the token, as a dictionary: each key is a claim's name.
"<name>"The claim's name. Any text works, a URL included.
<value>A string, a number, a bool, null, an array or a List<T>, or another Dictionary<string, object> for a JSON object.
<credentials>The key and algorithm that sign the token, here HS256.

Microsoft Learn's page for SecurityTokenDescriptor.Claims: "Gets or sets the Dictionary<TKey,TValue> which represents the claims that will be used when creating a security token."

The Example​

The example signs a token for a user named Ada with three custom claims of three JSON types: name, a string; roles, an array; and https://photos.example.org/quota, an object with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. Then the example validates the token, prints its payload and reads one value back.

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.25.0 here.

Step 2: Write the Code​

Replace the contents of Program.cs:

Program.cs, which creates a token with issuer, audience, a one-hour expiry and a Claims dictionary holding sub ada, name Ada, roles editor and viewer, and a dictionary under https://photos.example.org/quota with albums 10 and storage_gb 50, validates it with ValidateTokenAsync, prints the payload and reads albums from the quota.

Program.cs
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var key = new SymmetricSecurityKey(Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64="));
var handler = new JsonWebTokenHandler();

var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
Audience = "https://photos.example.org",
Expires = DateTime.UtcNow.AddHours(1),
Claims = new Dictionary<string, object>
{
["sub"] = "ada",
["name"] = "Ada", // a string
["roles"] = new[] { "editor", "viewer" }, // an array
["https://photos.example.org/quota"] = new Dictionary<string, object> // an object
{
["albums"] = 10,
["storage_gb"] = 50,
},
},
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
});
Console.WriteLine(token);

var result = await handler.ValidateTokenAsync(token, new TokenValidationParameters
{
IssuerSigningKey = key,
ValidIssuer = "https://login.example.org",
ValidAudience = "https://photos.example.org",
});
if (!result.IsValid)
{
throw result.Exception;
}
var verified = (JsonWebToken)result.SecurityToken;
Console.WriteLine(Base64UrlEncoder.Decode(verified.EncodedPayload));
var quota = verified.GetPayloadValue<Dictionary<string, object>>("https://photos.example.org/quota");
Console.WriteLine(quota["albums"]);
  • The Claims dictionary holds sub and the three custom claims. The comments name each value's JSON type.
  • roles is new[] { "editor", "viewer" }, a string array, which becomes a JSON array. A collection expression such as ["editor", "viewer"] doesn't compile here, because the dictionary's values are object.
  • The quota is another Dictionary<string, object>, which becomes a JSON object.
  • Issuer, Audience and Expires add the registered claims iss, aud and exp.
  • ValidateTokenAsync checks the signature, the issuer, the audience and the expiry. Base64UrlEncoder.Decode(verified.EncodedPayload) turns the payload back into JSON text, and GetPayloadValue<Dictionary<string, object>> reads the object claim as a dictionary.

Step 3: Run It​

Terminal
dotnet run
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL3Bob3Rvcy5leGFtcGxlLm9yZyIsImlzcyI6Imh0dHBzOi8vbG9naW4uZXhhbXBsZS5vcmciLCJleHAiOjE3OTYyOTE2NDQsInN1YiI6ImFkYSIsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9LCJpYXQiOjE3OTYyODgwNDQsIm5iZiI6MTc5NjI4ODA0NH0.rVaLh--Rez8d3HBagWBSsHrkQmdBDHxXXBvLnAER6p0
{"aud":"https://photos.example.org","iss":"https://login.example.org","exp":1796291644,"sub":"ada","name":"Ada","roles":["editor","viewer"],"https://photos.example.org/quota":{"albums":10,"storage_gb":50},"iat":1796288044,"nbf":1796288044}
10

A zsh terminal where dotnet run prints the token, then the payload with aud, iss, exp, sub ada, name Ada, roles editor and viewer, the quota object with albums 10 and storage_gb 50, iat and nbf, then 10.

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

What Happened​

  • The payload starts with aud, iss and exp from the descriptor's properties, then has the dictionary's claims in the order they were written, then iat and nbf. JsonWebTokenHandler adds those two by default: Learn's page for SetDefaultTimesOnTokenCreation says it "controls if token creation will set default 'exp', 'nbf' and 'iat' if not specified".
  • Each claim kept its JSON type. roles is an array and the quota an object, not text.
  • The last line read 10 from inside the object claim, after the token was validated.

Common Mistakes​

MistakeWhat happensDo this instead
A class or record of your own as a valueIDX11025: Cannot serialize object of type. See Fixed: "IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'" in .NET C#Use a Dictionary<string, object>
A collection expression such as ["editor", "viewer"] as a valueerror CS9174: Cannot initialize type 'object' with a collection expression because the type is not constructible.new[] { "editor", "viewer" }
A DateTime as a valueIt becomes text such as "2026-01-02T03:04:05.0000000Z", not a number of secondsnew DateTimeOffset(joined).ToUnixTimeSeconds() when the API expects seconds
Setting iss in Claims and with IssuerThe Issuer property's value wins, and the same goes for exp and ExpiresSet each registered claim one way
Reading custom claims from ReadJsonWebToken in an APINothing checks the signature, so anyone could have written themRead them from the token ValidateTokenAsync returns

Troubleshooting​

SymptomLikely causeFix
System.ArgumentException: IDX11025: Cannot serialize object of typeA claim's value has a type IdentityModel can't writeUse a dictionary, an array or a simple value
error CS9174: Cannot initialize type 'object' with a collection expression because the type is not constructible.A collection expression as a value in Dictionary<string, object>Use new[] { … }
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.GetPayloadValue asked for a claim the token doesn't haveCheck with TryGetPayloadValue first

FAQ​

Can a custom claim hold an object or an array?​

Yes. An array or a List<T> becomes a JSON array, and a Dictionary<string, object> becomes a JSON object, as the quota did.

Why does one claim have a URL as its name?​

Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.

Does JsonWebTokenHandler check my custom claims?​

No. ValidateTokenAsync checks the signature, the lifetime, and the issuer and audience you give it. Checking that roles is an array, or that the quota is there, is up to your code.

What if I set Subject as well as Claims?​

Learn's page for Claims says: "If both Claims and Subject are set, the claim values in Subject will be combined with the values in Claims. The values found in Claims take precedence over those found in Subject, so any duplicate values will be overridden."

Conclusion​

Put your claims in SecurityTokenDescriptor.Claims, and read them from the token ValidateTokenAsync returns. Use arrays and dictionaries for lists and objects, give claims that other services may see a URL name, and check each one's type before your code relies on it.

Additional Resources​