nilayparikh / Jwe

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

This library supports generating and decoding JSON Web Tokens.

Installation

Package is avaliable via NuGet. Or you can download and compile it yourself.

Supported .NET Framework versions

As of version 2.0, the lowest Supported version is 4.6.1

Usage

Creating (Encoding) Tokens

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

IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer);

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

Output will be:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s

Parsing (Decoding) and Verifying Tokens

var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s";
var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
try
{
    IJsonSerializer serializer = new JsonNetSerializer();
    IDateTimeProvider provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IJwtDecoder decoder = new JwtDecoder(serializer, validator);
    
    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");
}

Output will be:

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

You can also deserialize the JSON payload directly to a .NET type with DecodeToObject<T>:

var payload = decoder.DecodeToObject<IDictionary<string, object>>(token, secret);
Console.WriteLine(payload["claim2"]);

Output will be:

claim2-value

exp claim

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 an exp claim is present and is prior to the current time the token will fail verification. The exp (expiry) value must be specified as the number of seconds since 1/1/1970 UTC.

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

var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);

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

var json = decoder.Decode(token, secret); // TokenExpiredException

Custom JSON serializer

By default JSON serialization is done by JsonNetSerializer implemented using Json.Net. To configure a different one first implement the IJsonSerializer interface:

public 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 as a dependency to JwtEncoder constructor:

IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new CustomJsonSerializer();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer);

About

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

License:Other


Languages

Language:C# 99.3%Language:Batchfile 0.7%