Convert Figma logo to code with AI

jwt-dotnet logojwt

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

2,119
463
2,119
10

Top Related Projects

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

10,174

Java JWT: JSON Web Token for Java and Android

9,353

PHP package for JWT

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

7,251

A simple library to work with JSON Web Token and JSON Web Signature

Quick Overview

JWT-dotnet is a popular .NET implementation for JSON Web Tokens (JWT). It provides a simple and secure way to create, encode, decode, and validate JWTs in .NET applications, supporting various algorithms and offering flexibility in token handling.

Pros

  • Easy to use with a fluent API design
  • Supports multiple JWT algorithms (HMAC, RSA, ECDSA)
  • Actively maintained with regular updates
  • Extensive documentation and community support

Cons

  • Limited built-in support for some advanced JWT features
  • Performance may be slightly lower compared to some alternatives
  • Requires careful handling of secret keys and token validation to ensure security
  • Some users report occasional issues with specific edge cases

Code Examples

Creating and encoding a JWT:

var token = JwtBuilder.Create()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret("your-256-bit-secret")
    .AddClaim("sub", "1234567890")
    .AddClaim("name", "John Doe")
    .AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
    .Encode();

Decoding and validating a JWT:

try
{
    var json = JwtBuilder.Create()
        .WithAlgorithm(new HMACSHA256Algorithm())
        .WithSecret("your-256-bit-secret")
        .MustVerifySignature()
        .Decode(token);
    
    Console.WriteLine(json);
}
catch (TokenExpiredException)
{
    Console.WriteLine("Token has expired");
}
catch (SignatureVerificationException)
{
    Console.WriteLine("Token has invalid signature");
}

Using RSA algorithm for JWT signing:

var privateKey = "your-private-key";
var publicKey = "your-public-key";

var token = JwtBuilder.Create()
    .WithAlgorithm(new RS256Algorithm(publicKey, privateKey))
    .AddClaim("sub", "1234567890")
    .Encode();

var json = JwtBuilder.Create()
    .WithAlgorithm(new RS256Algorithm(publicKey))
    .MustVerifySignature()
    .Decode(token);

Getting Started

  1. Install the package via NuGet:

    dotnet add package JWT
    
  2. Add the necessary using statements:

    using JWT;
    using JWT.Algorithms;
    using JWT.Serializers;
    
  3. Create and encode a simple JWT:

    var token = JwtBuilder.Create()
        .WithAlgorithm(new HMACSHA256Algorithm())
        .WithSecret("your-secret-key")
        .AddClaim("sub", "user123")
        .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
        .Encode();
    
  4. Decode and validate the JWT:

    var json = JwtBuilder.Create()
        .WithAlgorithm(new HMACSHA256Algorithm())
        .WithSecret("your-secret-key")
        .MustVerifySignature()
        .Decode(token);
    

Competitor Comparisons

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Pros of node-jsonwebtoken

  • Larger community and more frequent updates
  • Supports a wider range of algorithms
  • Better documentation and examples

Cons of node-jsonwebtoken

  • Limited to Node.js environment
  • Slightly more complex API for some operations

Code Comparison

node-jsonwebtoken:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secret');

jwt:

var token = JWT.Encode(payload, secret, JwsAlgorithm.HS256);
var json = JWT.Decode(token, secret, JwsAlgorithm.HS256);

Key Differences

  • Language: node-jsonwebtoken is for JavaScript/Node.js, while jwt is for .NET
  • API Design: node-jsonwebtoken uses separate sign and verify methods, jwt combines encoding and decoding in single methods
  • Ecosystem: node-jsonwebtoken has a larger npm ecosystem, jwt integrates well with .NET projects
  • Performance: jwt may have better performance in .NET environments due to native compilation

Use Cases

  • Choose node-jsonwebtoken for Node.js projects or when working in JavaScript ecosystems
  • Opt for jwt in .NET applications or when C# is the primary language
  • Consider node-jsonwebtoken for projects requiring a wide range of JWT algorithms
  • Select jwt for better integration with other .NET libraries and frameworks
10,174

Java JWT: JSON Web Token for Java and Android

Pros of jjwt

  • Written in Java, offering better integration with Java-based projects
  • More comprehensive documentation and examples
  • Actively maintained with frequent updates and releases

Cons of jjwt

  • Limited to Java ecosystem, less versatile for cross-platform development
  • May have a steeper learning curve for developers not familiar with Java

Code Comparison

jwt-dotnet/jwt (C#):

var token = JWT.Encode(payload, secret, JwsAlgorithm.HS256);
var json = JWT.Decode(token, secret);

jwtk/jjwt (Java):

String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, secret).compact();
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();

Both libraries provide similar functionality for encoding and decoding JWTs, with syntax differences reflecting their respective programming languages. jwt-dotnet/jwt offers a more concise API, while jjwt provides a more explicit builder pattern approach.

9,353

PHP package for JWT

Pros of php-jwt

  • Lightweight and simple implementation, easy to integrate into PHP projects
  • Supports various algorithms (HS256, RS256, etc.) for token signing and verification
  • Well-documented with clear examples in the README

Cons of php-jwt

  • Limited to PHP ecosystem, while jwt-dotnet supports multiple .NET platforms
  • Fewer built-in features compared to jwt-dotnet (e.g., no automatic JWT validation)
  • Less active development and community engagement

Code Comparison

php-jwt:

use Firebase\JWT\JWT;

$payload = ['user_id' => 123];
$jwt = JWT::encode($payload, $key, 'HS256');
$decoded = JWT::decode($jwt, $key, ['HS256']);

jwt-dotnet:

var token = JwtBuilder.Create()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(secret)
    .AddClaim("user_id", 123)
    .Encode();

var payload = JwtBuilder.Create()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(secret)
    .MustVerifySignature()
    .Decode(token);

Both libraries provide straightforward methods for encoding and decoding JWTs, but jwt-dotnet offers a more fluent API with additional built-in features for token validation and claim management.

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Pros of jwt-auth

  • Built specifically for Laravel, offering seamless integration with the framework
  • Provides a more comprehensive authentication solution, including user management
  • Offers additional features like token blacklisting and refresh tokens

Cons of jwt-auth

  • Limited to Laravel applications, less versatile than jwt-dotnet
  • May have a steeper learning curve for developers not familiar with Laravel
  • Less frequently updated compared to jwt-dotnet

Code Comparison

jwt-auth (Laravel):

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::toUser($token);
JWTAuth::invalidate($token);

jwt-dotnet (.NET):

var token = JWT.Encode(payload, secret, JwsAlgorithm.HS256);
var json = JWT.Decode(token, secret);
var decodedToken = JWT.Decode(token, secret, JwsAlgorithm.HS256);

Summary

jwt-auth is a Laravel-specific JWT implementation offering robust authentication features, while jwt-dotnet is a more versatile .NET library for JWT encoding and decoding. jwt-auth provides a more complete authentication solution for Laravel applications but is limited to that framework. jwt-dotnet offers greater flexibility across different .NET projects but may require additional work to implement full authentication systems.

7,251

A simple library to work with JSON Web Token and JSON Web Signature

Pros of jwt

  • Written in PHP, offering native integration for PHP applications
  • Supports a wide range of algorithms, including EdDSA
  • Provides a fluent interface for token creation and parsing

Cons of jwt

  • Limited to PHP ecosystem, less versatile for cross-platform development
  • May have a steeper learning curve for developers not familiar with PHP
  • Less actively maintained compared to jwt-dotnet

Code Comparison

jwt (PHP):

$token = (new Builder())
    ->issuedBy('http://example.com')
    ->withClaim('uid', 1)
    ->getToken(new Sha256(), new Key('secret'));

jwt-dotnet (C#):

var token = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret("secret")
    .AddClaim("iss", "http://example.com")
    .AddClaim("uid", 1)
    .Build();

Both libraries offer similar functionality for creating JWT tokens, but with syntax specific to their respective languages. The jwt library uses a more fluent interface, while jwt-dotnet follows a builder pattern. jwt-dotnet is more versatile for .NET developers and offers cross-platform support, making it suitable for a wider range of applications. However, jwt may be preferable for PHP-specific projects due to its native integration and specialized features for the PHP ecosystem.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build status Release status

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

This library supports generating and decoding JSON Web Tokens.

Sponsor

Sponsor wanted or just buy me a coffee. Thanks!

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