Skip to main content

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

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

In .NET C#, SecurityTokenDescriptor has a property for five of the seven registered JWT claims: Issuer, Audience, IssuedAt, NotBefore and Expires. The other two, sub and jti, go in its Claims dictionary, and JsonWebTokenHandler.CreateToken signs the result.

Syntax​

Syntax
var token = new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
Issuer = "<iss>",
Audience = "<aud>",
IssuedAt = <DateTime>,
NotBefore = <DateTime>,
Expires = <DateTime>,
Claims = new Dictionary<string, object> { ["sub"] = "<sub>", ["jti"] = "<jti>" },
SigningCredentials = <credentials>,
});
PartWhat it does
Issuer, AudienceWrite iss and aud. Audiences takes a list when a token is for several APIs.
IssuedAt, NotBefore, ExpiresWrite iat, nbf and exp from DateTime values in UTC.
ClaimsA dictionary for every other claim, here sub and jti.
SigningCredentialsThe key and the algorithm that sign the token.

Microsoft Learn describes the three times on SecurityTokenDescriptor: IssuedAt "Gets or sets the time the security token was issued. This value should be in UTC.", and NotBefore and Expires are described the same way.

The Example​

The example signs a token for a user named ada, issued by https://login.example.org for https://photos.example.org, with iat and nbf set to now, exp two hours later and a random jti, and prints its payload. Then it signs a second token with only an issuer, to show which claims CreateToken adds on its own.

Prerequisites​

  • The .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 makes a console app, and dotnet package add installs Microsoft.IdentityModel.JsonWebTokens, version 8.23.0 here.

Step 2: Write the Code​

Replace the contents of Program.cs:

Program.cs, which fills a SecurityTokenDescriptor with Issuer, Audience, IssuedAt, NotBefore, Expires two hours ahead and sub and jti in Claims, prints the token and its decoded payload, then creates a token with only an Issuer and prints its payload.

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 secret = Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=");
var key = new SymmetricSecurityKey(secret);
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var handler = new JsonWebTokenHandler();

var now = DateTime.UtcNow;
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
Audience = "https://photos.example.org",
IssuedAt = now,
NotBefore = now,
Expires = now.AddHours(2),
Claims = new Dictionary<string, object>
{
["sub"] = "ada",
["jti"] = Guid.NewGuid().ToString(),
},
SigningCredentials = credentials,
});
Console.WriteLine(token);
Console.WriteLine(Base64UrlEncoder.Decode(handler.ReadJsonWebToken(token).EncodedPayload));

// Without IssuedAt, NotBefore and Expires, CreateToken fills in all three.
var minimal = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
SigningCredentials = credentials,
});
Console.WriteLine(Base64UrlEncoder.Decode(handler.ReadJsonWebToken(minimal).EncodedPayload));

ReadJsonWebToken(token).EncodedPayload is the token's middle piece, and Base64UrlEncoder.Decode turns it back into JSON, so the program can show exactly what was written.

Step 3: Run It​

Terminal
dotnet run
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL3Bob3Rvcy5leGFtcGxlLm9yZyIsImlzcyI6Imh0dHBzOi8vbG9naW4uZXhhbXBsZS5vcmciLCJleHAiOjE3OTYwNjY1NzEsImlhdCI6MTc5NjA1OTM3MSwibmJmIjoxNzk2MDU5MzcxLCJzdWIiOiJhZGEiLCJqdGkiOiI1NzYzMGM5MS1hMWVhLTRjNWEtOThjMC0zYWRhMzJlNmY5ZWEifQ.6F6Rn10i0NqjpqlbiUkZ-yFcpA5C6DQV2AIRAWIo9fE
{"aud":"https://photos.example.org","iss":"https://login.example.org","exp":1796066571,"iat":1796059371,"nbf":1796059371,"sub":"ada","jti":"57630c91-a1ea-4c5a-98c0-3ada32e6f9ea"}
{"iss":"https://login.example.org","exp":1796062972,"iat":1796059372,"nbf":1796059372}

A zsh terminal where dotnet run prints the token, its payload with aud, iss, exp, iat, nbf, sub and jti, and a second payload with only iss, exp, iat and nbf, where exp is 3600 higher than iat.

What Happened​

  • All seven claims are there, but not in the order the code set them: aud and iss come first, then the times, then the Claims dictionary. The order doesn't matter, because every library reads claims by name.
  • exp is 7200 higher than iat: now.AddHours(2) in seconds.
  • The second token got exp, iat and nbf without asking. CreateToken set iat and nbf to now and exp an hour later. Learn describes the setting behind it, SetDefaultTimesOnTokenCreation: it "controls if token creation will set default 'exp', 'nbf' and 'iat' if not specified."

Common Mistakes​

MistakeWhat happensDo this instead
Passing DateTime.NowLearn says the values "should be in UTC"Use DateTime.UtcNow
Putting aud in Claims as well as setting AudienceLearn says Audience "Will be combined with Audiences and any "Aud" claims in Claims", so the token can name two audiencesSet the audience in one place
Relying on the default hourEvery token lives an hour, whether you meant it or notSet Expires yourself

Troubleshooting​

SymptomLikely causeFix
The token has no iss or audIssuer or Audience wasn't setSet them on the descriptor
exp is an hour after iat though you never set itCreateToken added the default timesSet Expires, or turn off SetDefaultTimesOnTokenCreation on the handler

FAQ​

How do I give a token several audiences?​

Add them to the descriptor's Audiences list instead of setting Audience. Learn says they're "combined" into the token's aud claim.

Can I set sub with the Subject property?​

Subject is a ClaimsIdentity, a collection of claims, not the sub claim itself. The Claims dictionary is the direct way to write sub.

Conclusion​

Set Issuer, Audience, IssuedAt, NotBefore and Expires on the descriptor, put sub and jti in Claims, and CreateToken writes all seven. Leave the times out and it adds them, with an hour's lifetime.

Additional Resources​