JWT.Extensions.AspNetCore 11.1.0

dotnet add package JWT.Extensions.AspNetCore --version 11.1.0
                    
NuGet\Install-Package JWT.Extensions.AspNetCore -Version 11.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="JWT.Extensions.AspNetCore" Version="11.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="JWT.Extensions.AspNetCore" Version="11.1.0" />
                    
Directory.Packages.props
<PackageReference Include="JWT.Extensions.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add JWT.Extensions.AspNetCore --version 11.1.0
                    
#r "nuget: JWT.Extensions.AspNetCore, 11.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package JWT.Extensions.AspNetCore@11.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=JWT.Extensions.AspNetCore&version=11.1.0
                    
Install as a Cake Addin
#tool nuget:?package=JWT.Extensions.AspNetCore&version=11.1.0
                    
Install as a Cake Tool

Build status Release status

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

This library supports generating and decoding JSON Web Tokens.

<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 using favorite JSON serializer
    }

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

And then pass this serializer to JwtEncoder constructor:

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:

JsonSerializer customJsonSerializer = new JsonSerializer
{
    // All keys start with lowercase characters instead of the exact casing of the model/property, e.g. fullName
    ContractResolver = new CamelCasePropertyNamesContractResolver(), 
    
    // Nice and easy to read, but you can also use Formatting.None to reduce the payload size
    Formatting = Formatting.Indented,
    
    // The most appropriate datetime format.
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    
    // Don't add keys/values when the value is null.
    NullValueHandling = NullValueHandling.Ignore,
    
    // Use the enum string value, not the implicit int value, e.g. "red" for enum Color { Red }
    Converters.Add(new StringEnumConverter())
};
IJsonSerializer serializer = new JsonNetSerializer(customJsonSerializer);

Jwt.Net ASP.NET Core

Register authentication handler to validate JWT

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
                 {
                     options.DefaultAuthenticateScheme = JwtAuthenticationDefaults.AuthenticationScheme;
                     options.DefaultChallengeScheme = JwtAuthenticationDefaults.AuthenticationScheme;
                 })
            .AddJwt(options =>
                 {
                     // secrets, required only for symmetric algorithms, such as HMACSHA256Algorithm
                     // options.Keys = new[] { "mySecret" };
                     
                     // optionally; disable throwing an exception if JWT signature is invalid
                     // options.VerifySignature = false;
                 });
  // the non-generic version AddJwt() requires registering an instance of IAlgorithmFactory manually
  services.AddSingleton<IAlgorithmFactory>(new RSAlgorithmFactory(certificate));
  // or
  services.AddSingleton<IAlgorithmFactory>(new DelegateAlgorithmFactory(algorithm));

  // or use the generic version AddJwt<TFactory() to use a custom implementation of IAlgorithmFactory
  .AddJwt<MyCustomAlgorithmFactory>(options => ...);
}

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
}

Custom factories to produce Identity or AuthenticationTicket

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
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on JWT.Extensions.AspNetCore:

Package Downloads
AppStoreServerApi-TempFork

This is just a temporary fork that hosts the repo on nuget until the original author does it. Original project here: https://github.com/dragouf/AppStoreServerApi

KonH.AppStoreServerApi

Library to access some endpoints of Apple AppStore Server API (https://developer.apple.com/documentation/appstoreserverapi) Fork of https://github.com/dragouf/AppStoreServerApi

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.1.0 0 7/6/2026
11.1.0-beta1 102 6/3/2026
11.0.0-beta4 40,306 5/29/2024
11.0.0-beta3 268 4/29/2024
11.0.0-beta2 230 4/28/2024
11.0.0-beta1 205 4/28/2024
10.1.1 529,027 2/1/2023
10.1.0 4,252 1/18/2023
10.0.1 1,262 1/18/2023
10.0.0 3,367 1/6/2023
10.0.0-beta4 1,934 9/8/2022
10.0.0-beta3 1,140 7/28/2022
10.0.0-beta2 926 6/23/2022
10.0.0-beta1 834 6/18/2022
9.1.0-beta1 894 6/23/2022
9.0.0 44,374 4/27/2022
9.0.0-beta2 900 4/10/2022
9.0.0-beta1 967 2/14/2022
8.2.0 39,692 1/1/2022
Loading failed