Project Name | Stars | Downloads | Repos Using This | Packages Using This | Most Recent Commit | Total Releases | Latest Release | Open Issues | License | Language |
---|---|---|---|---|---|---|---|---|---|---|
Opa | 8,069 | 82 | 279 | 17 hours ago | 564 | September 07, 2022 | 312 | apache-2.0 | Go | |
An open source, general-purpose policy engine. | ||||||||||
Jwt | 1,974 | 313 | 305 | 2 months ago | 122 | September 26, 2022 | 8 | other | C# | |
Jwt.Net, a JWT (JSON Web Token) implementation for .NET | ||||||||||
Spring Boot Jwt | 1,022 | a year ago | mit | Java | ||||||
JWT auth service using Spring Boot, Spring Security and MySQL | ||||||||||
Oscal | 543 | 3 days ago | 207 | other | XSLT | |||||
Open Security Controls Assessment Language (OSCAL) | ||||||||||
Hiauth | 304 | 3 months ago | 2 | mit | TypeScript | |||||
HiAuth是一个开源的基于Oauth2协议的认证、授权系统。 | ||||||||||
Fedramp Automation | 193 | 2 days ago | 142 | other | TypeScript | |||||
FedRAMP Automation | ||||||||||
Json Server Auth | 147 | 12 | 6 | 2 years ago | 9 | July 21, 2021 | 7 | mit | TypeScript | |
Authentication & Authorization flow for JSON Server | ||||||||||
Spring Boot Oauth2 Jwt Swagger Ui | 103 | a month ago | 4 | mit | Java | |||||
Spring Boot , OAuth 2 , JWT (Json Web Token) and Swagger UI | ||||||||||
Gin Api Demo | 81 | 5 years ago | June 02, 2021 | Go | ||||||
An example of using the Gin framework in Go to create a JSON api with most of the core functionality a JSON api needs. | ||||||||||
Core | 74 | 17 hours ago | 3 | apache-2.0 | Java | |||||
AuthzForce Core PDP engine (Community Edition) |
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);
var token = encoder.Encode(payload);
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);
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");
}
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
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.
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
JwtHeader header = JwtBuilder.Create()
.DecodeHeader<JwtHeader>(token);
var typ = header.Type; // JWT
var alg = header.Algorithm; // RS256
var kid = header.KeyId; // CFAEAE2D650A6CA9862575DE54371EA980643849
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
var 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:
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);
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();
}
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.