SkillAgentSearch skills...

Jwt

Jwt.Net, a JWT (JSON Web Token) implementation for .NET

Install / Use

/learn @jwt-dotnet/Jwt
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DO NOT EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <!-- END doctoc generated TOC please keep comment here to allow auto update -->

Build status Release status

Jwt.Net, a JWT (JSON Web Token) implementation for .NET

This library supports generating and decoding JSON Web Tokens.

Sponsor

| | | |-|-| | <img alt="Auth0 logo" src="https://cdn.auth0.com/blog/github-sponsorships/brand-evolution-logo-Auth0-horizontal-Indigo.png" height="91"> | If you want to quickly implement a secure authentication to your JWT project, create an Auth0 account; it's Free! |

Avaliable NuGet packages

  1. Jwt.Net

NuGet NuGet Pre

  1. Jwt.Net for Microsoft Dependency Injection container

NuGet NuGet Pre

  1. Jwt.Net for ASP.NET Core

NuGet NuGet Pre

Supported .NET versions:

  • .NET Framework 3.5
  • .NET Framework 4.0 - 4.8
  • .NET Standard 1.3, 2.0
  • .NET 6.0

Jwt.NET

Creating (encoding) token

var payload = new Dictionary<string, object>
{
    { "claim1", 0 },
    { "claim2", "claim2-value" }
};

IJwtAlgorithm algorithm = new RS256Algorithm(certificate);
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
const string key = null; // not needed if algorithm is asymmetric

var token = encoder.Encode(payload, key);
Console.WriteLine(token);

Or using the fluent builder API

var token = JwtBuilder.Create()
                      .WithAlgorithm(new RS256Algorithm(certificate))
                      .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
                      .AddClaim("claim1", 0)
                      .AddClaim("claim2", "claim2-value")
                      .Encode();
Console.WriteLine(token);

Parsing (decoding) and verifying token

try
{
    IJsonSerializer serializer = new JsonNetSerializer();
    IDateTimeProvider provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtAlgorithm algorithm = new RS256Algorithm(certificate);
    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
    
    var json = decoder.Decode(token);
    Console.WriteLine(json);
}
catch (TokenNotYetValidException)
{
    Console.WriteLine("Token is not valid yet");
}
catch (TokenExpiredException)
{
    Console.WriteLine("Token has expired");
}
catch (SignatureVerificationException)
{
    Console.WriteLine("Token has invalid signature");
}

Or using the fluent builder API

var json = JwtBuilder.Create()
                     .WithAlgorithm(new RS256Algorithm(certificate))
                     .MustVerifySignature()
                     .Decode(token);                    
Console.WriteLine(json);

The output would be:

{ "claim1": 0, "claim2": "claim2-value" }

You can also deserialize the JSON payload directly to a .NET type:

var payload = decoder.DecodeToObject<IDictionary<string, object>>(token, secret);

Or using the fluent builder API

var payload = JwtBuilder.Create()
                        .WithAlgorithm(new RS256Algorithm(certificate))
                        .WithSecret(secret)
                        .MustVerifySignature()
                        .Decode<IDictionary<string, object>>(token);     

Validate token expiration

As described in the RFC 7519 section 4.1.4:

The exp claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.

If it is present in the payload and is past the current time, the token will fail verification. The value must be specified as the number of seconds since the Unix epoch, 1/1/1970 00:00:00 UTC.

IDateTimeProvider provider = new UtcDateTimeProvider();
var now = provider.GetNow().AddMinutes(-5); // token has expired 5 minutes ago

double secondsSinceEpoch = UnixEpoch.GetSecondsSince(now);

var payload = new Dictionary<string, object>
{
    { "exp", secondsSinceEpoch }
};
var token = encoder.Encode(payload);

decoder.Decode(token); // throws TokenExpiredException

Then, as described in the RFC 7519 section 4.1.5:

The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing

If it is present in the payload and is prior to the current time, the token will fail verification.

Parsing (decoding) token header

IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, urlEncoder);

JwtHeader header = decoder.DecodeHeader<JwtHeader>(token);

var typ = header.Type; // JWT
var alg = header.Algorithm; // RS256
var kid = header.KeyId; // CFAEAE2D650A6CA9862575DE54371EA980643849

Or using the fluent builder API

JwtHeader header = JwtBuilder.Create()
                             .DecodeHeader<JwtHeader>(token);

var typ = header.Type; // JWT
var alg = header.Algorithm; // RS256
var kid = header.KeyId; // CFAEAE2D650A6CA9862575DE54371EA980643849

Turning off parts of token validation

If you'd like to validate a token but ignore certain parts of the validation (such as whether to the token has expired or not valid yet), you can pass a ValidateParameters object to the constructor of the JwtValidator class.

var validationParameters = new ValidationParameters
{
    ValidateSignature = true,
    ValidateExpirationTime = false,
    ValidateIssuedTime = false,
    TimeMargin = 100
};
IJwtValidator validator = new JwtValidator(serializer, provider, validationParameters);
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var json = decoder.Decode(expiredToken); // will not throw because of expired token

Or using the fluent builder API

var json = JwtBuilder.Create()
                     .WithAlgorithm(new RS256Algorirhm(certificate))
                     .WithSecret(secret)
                     .WithValidationParameters(
                         new ValidationParameters
                         {
                             ValidateSignature = true,
                             ValidateExpirationTime = false,
                             ValidateIssuedTime = false,
                             TimeMargin = 100
                         })
                     .Decode(expiredToken);

Custom JSON serializer

By default JSON serialization is performed by JsonNetSerializer implemented using Json.Net. To use a different one, implement the IJsonSerializer interface:

public sealed class CustomJsonSerializer : IJsonSerializer
{
    public string Serialize(object obj)
    {
        // Implement 
View on GitHub
GitHub Stars2.2k
CategoryDevelopment
Updated14d ago
Forks469

Languages

C#

Security Score

85/100

Audited on Mar 16, 2026

No findings