Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

jwt

> 安全
Open source

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

2.2K stars0 likes0 views
WebsiteGitHub

About

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

  • Jwt.Net, a JWT (JSON Web Token) implementation for .NET
  • Sponsor
  • Avaliable NuGet packages
  • Supported .NET versions:
  • Jwt.NET
    • Creating (encoding) token
      • Or using the fluent builder API
    • Parsing (decoding) and verifying token
      • Or using the fluent builder API
      • Or using the fluent builder API
    • Validate token expiration
    • Parsing (decoding) token header
      • Or using the fluent builder API
    • Turning off parts of token validation
      • Or using the fluent builder API
    • Custom JSON serializer
    • Custom JSON serialization settings with the default JsonNetSerializer
  • Jwt.Net ASP.NET Core
    • Register authentication handler to validate JWT
    • Custom factories to produce Identity or AuthenticationTicket
  • License

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

This library supports generating and decoding JSON Web Tokens.

Sponsor

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
  2. Jwt.Net for Microsoft Dependency Injection container
  3. Jwt.Net for ASP.NET Core

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

csharp
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

csharp
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

…

Or using the fluent builder API

csharp
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:

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

Or using the fluent builder API

csharp
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.

csharp
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

csharp
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

csharp
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.

csharp
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

csharp
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:

csharp
public sealed class CustomJsonSerializer : IJsonSerializer
{
    public string Serialize(object obj)
    {
        // Implement using favorite JSON serializer
    }

    public T Deserialize<T>(string json)
    {
        // Implement using favorite JSON serializer
    }
}

And then pass this serializer to JwtEncoder constructor:

csharp
IJwtAlgorithm algorithm = new RS256Algorirhm(certificate);
IJsonSerializer serializer = new CustomJsonSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

Custom JSON serialization settings with the default JsonNetSerializer

As mentioned above, the default JSON serialization is done by JsonNetSerializer. You can define your own custom serialization settings as follows:

…

Jwt.Net ASP.NET Core

Register authentication handler to validate JWT

…

Custom factories to produce Identity or AuthenticationTicket

csharp
services.AddSingleton<IIdentityFactory, CustomIdentityFctory>();
services.AddSingleton<ITicketFactory, CustomTicketFactory>();

License

The following projects and their resulting packages are licensed under Public Domain, see the LICENSE#Public-Domain file.

  • JWT

The following projects and their resulting packages are licensed under the MIT License, see the LICENSE#MIT file.

  • JWT.Extensions.AspNetCore
  • JWT.Extensions.DependencyInjection

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#authorizationc-sharpjsonjwt

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category安全
PricingOpen source

> Related tools

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.