All Projects → jwt-dotnet → Jwt

jwt-dotnet / Jwt

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

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to Jwt

Access
Ponzu Addon to manage API access grants and tokens for authentication
Stars: ✭ 13 (-99.23%)
Mutual labels:  jwt, authorization
Authex
Authex is an opinionated JWT authentication and authorization library for Elixir.
Stars: ✭ 73 (-95.69%)
Mutual labels:  jwt, authorization
Grpc Auth Example
Examples of client authentication with gRPC
Stars: ✭ 65 (-96.16%)
Mutual labels:  jwt, authorization
Jose Jwt
Ultimate Javascript Object Signing and Encryption (JOSE) and JSON Web Token (JWT) Implementation for .NET and .NET Core
Stars: ✭ 692 (-59.15%)
Mutual labels:  json, jwt
Express Jwt
An example API for creating/verifying json web tokens
Stars: ✭ 105 (-93.8%)
Mutual labels:  jwt, authorization
Auth0.js
Auth0 headless browser sdk
Stars: ✭ 755 (-55.43%)
Mutual labels:  jwt, authorization
Nextjs Jwt Example
next.js authorization example including private route protection
Stars: ✭ 72 (-95.75%)
Mutual labels:  jwt, authorization
Cerberus
A demonstration of a completely stateless and RESTful token-based authorization system using JSON Web Tokens (JWT) and Spring Security.
Stars: ✭ 482 (-71.55%)
Mutual labels:  jwt, authorization
Hs Jose
Haskell JOSE and JWT library
Stars: ✭ 100 (-94.1%)
Mutual labels:  json, jwt
Micro Jwt Auth
jwt authorization wrapper for https://github.com/zeit/micro
Stars: ✭ 97 (-94.27%)
Mutual labels:  jwt, authorization
Jwt Framework
JWT Framework
Stars: ✭ 577 (-65.94%)
Mutual labels:  json, jwt
Spring Webmvc Pac4j
Security library for Spring Web MVC: OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...
Stars: ✭ 110 (-93.51%)
Mutual labels:  jwt, authorization
Full Stack Fastapi Postgresql
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.
Stars: ✭ 7,635 (+350.71%)
Mutual labels:  json, jwt
Jose
JSON Object Signing and Encryption for Node.js and the browser
Stars: ✭ 25 (-98.52%)
Mutual labels:  json, jwt
Opa
An open source, general-purpose policy engine.
Stars: ✭ 5,939 (+250.59%)
Mutual labels:  json, authorization
Spring Boot Webflux Jjwt
Example Spring Boot and WebFlux (Reactive Web) with Spring Security and JWT for token Authentication and Authorization
Stars: ✭ 71 (-95.81%)
Mutual labels:  jwt, authorization
Cloudfront Auth
An AWS CloudFront [email protected] function to authenticate requests using Google Apps, Microsoft, Auth0, OKTA, and GitHub login
Stars: ✭ 471 (-72.2%)
Mutual labels:  jwt, authorization
Jose
🔐 JSON Object Signing and Encryption Framework (JWT, JWS, JWE, JWA, JWK, JWKSet and more)
Stars: ✭ 479 (-71.72%)
Mutual labels:  json, jwt
Spring Security React Ant Design Polls App
Full Stack Polls App built using Spring Boot, Spring Security, JWT, React, and Ant Design
Stars: ✭ 1,336 (-21.13%)
Mutual labels:  jwt, authorization
Sample Spring Oauth2 Microservices
some examples that show basic and more advanced implementations of oauth2 authorization mechanism in spring-cloud microservices environment
Stars: ✭ 109 (-93.57%)
Mutual labels:  jwt, authorization

Build status Release status

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

This library supports generating and decoding JSON Web Tokens.

Sponsor

Auth0 logo If you want to quickly implement a secure authentication to your JWT project, create an Auth0 account; it's Free!

Avaliable 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
  • .NET Standard 2.0
  • .NET 5.0

Jwt.NET

Creating (encoding) token

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

IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

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

Or using the fluent builder API

var token = JwtBuilder.Create()
                      .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                      .WithSecret(secret)
                      .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
                      .AddClaim("claim2", "claim2-value")
                      .Encode();

Console.WriteLine(token);

The output would be:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s

Parsing (decoding) and verifying token

const string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s";
const string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";

try
{
    IJsonSerializer serializer = new JsonNetSerializer();
    IDateTimeProvider provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
    
    var json = decoder.Decode(token, secret, verify: true);
    Console.WriteLine(json);
}
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 HMACSHA256Algorithm()) // symmetric
                     .WithSecret(secret)
                     .MustVerifySignature()
                     .Decode(token);                    
Console.WriteLine(json);

or

var json = JwtBuilder.Create()
                     .WithAlgorithm(new RS256Algorithm(certificate)) // asymmetric
                     .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);
Console.WriteLine(payload["claim2"]);

Or using the fluent builder API

var payload = JwtBuilder.Create()
                        .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                        .WithSecret(secret)
                        .MustVerifySignature()
                        .Decode<IDictionary<string, object>>(token);     
Console.WriteLine(payload["claim2"]);

and

var payload = JwtBuilder.Create()
                        .WithAlgorithm(new RS256Algorithm(certificate)) // asymmetric
                        .MustVerifySignature()
                        .Decode<IDictionary<string, object>>(token);     
Console.WriteLine(payload["claim2"]);

The output would be:

claim2-value

Set and validate token expiration

As described in the JWT RFC:

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 prior to 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 UTC.

IDateTimeProvider provider = new UtcDateTimeProvider();
var now = provider.GetNow();

double  secondsSinceEpoch = UnixEpoch.GetSecondsSince(now);

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

var json = decoder.Decode(token, secret, validate: true); // throws TokenExpiredException

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

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 HMACSHA256Algorithm(); // symmetric
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
                     options.Keys = new[] { "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" };
                     
                     // force JwtDecoder to throw exception if JWT signature is invalid
                     options.VerifySignature = true;
                 });
  // the non-generic version AddJwt() requires you to register 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() if you have a custom implementation of IAlgorithmFactory
  // AddJwt<MyCustomAlgorithmFactory(options => ...);
}

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

Custom factories to produce Identity or AuthenticationTicket

options.IdentityFactory = dic => new ClaimsIdentity(
    dic.Select(p => new Claim(p.Key, p.Value)));

options.TicketFactory = (identity, scheme) => new AuthenticationTicket(
    new ClaimsPrincipal(identity),
    new AuthenticationProperties(),
    scheme.Name);

Register middleware to validate JWT

services.AddAuthentication(options =>
    {
        // Prevents from System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found.
        options.DefaultAuthenticateScheme = JwtAuthenticationDefaults.AuthenticationScheme;

        // Prevents from System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
        options.DefaultChallengeScheme = JwtAuthenticationDefaults.AuthenticationScheme;
    })
.AddJwt(options =>
    {
        options.Keys = configureOptions.Keys;
        options.VerifySignature = configureOptions.VerifySignature;
    });

Jwt.Net OWIN

NuGet

NuGet NuGet Pre

Register middleware to validate JWT

app.UseJwtMiddleware();

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

Note: work in progress as the scenario/usage is not designed yet. The registered component will do nothing but throw an exception.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].