Jwt.Net, a JWT (JSON Web Token) implementation for .NET
This library supports generating and decoding JSON Web Tokens.
| If you want to quickly implement a secure authentication to your JWT project, create an Auth0 account; it's Free! |
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);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);…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);var payload = JwtBuilder.Create()
.WithAlgorithm(new RS256Algorithm(certificate))
.WithSecret(secret)
.MustVerifySignature()
.Decode<IDictionary<string, object>>(token); As described in the RFC 7519 section 4.1.4:
The
expclaim 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 TokenExpiredExceptionThen, 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.
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; // CFAEAE2D650A6CA9862575DE54371EA980643849JwtHeader header = JwtBuilder.Create()
.DecodeHeader<JwtHeader>(token);
var typ = header.Type; // JWT
var alg = header.Algorithm; // RS256
var kid = header.KeyId; // CFAEAE2D650A6CA9862575DE54371EA980643849If 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 tokenvar json = JwtBuilder.Create()
.WithAlgorithm(new RS256Algorirhm(certificate))
.WithSecret(secret)
.WithValidationParameters(
new ValidationParameters
{
ValidateSignature = true,
ValidateExpirationTime = false,
ValidateIssuedTime = false,
TimeMargin = 100
})
.Decode(expiredToken);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);As mentioned above, the default JSON serialization is done by JsonNetSerializer. You can define your own custom serialization settings as follows:
……services.AddSingleton<IIdentityFactory, CustomIdentityFctory>();
services.AddSingleton<ITicketFactory, CustomTicketFactory>();The following projects and their resulting packages are licensed under Public Domain, see the LICENSE#Public-Domain file.
The following projects and their resulting packages are licensed under the MIT License, see the LICENSE#MIT file.
No open issues yet, or sync has not completed.