JSON Web Token implementation for .NET based on RFC 7519.
You can use the JsonWebToken
class to create a token using the method CreateToken()
.
var key = Encoding.UTF8.GetBytes("secret");
var jsongWebToken = new JsonWebToken();
var token = jsongWebToken.CreateToken(key);
It is also possible to call CreateToken()
passing a payload (also known as claims) and an Expiration Time. The following code will create a token that will expire in 10 minutes from the current UTC time.
var key = Encoding.UTF8.GetBytes("secret");
var claims = new Dictionary<string, object>
{
{ "name", "John Doe" },
{ "admin", true }
};
var token = jsongWebToken.CreateToken(key, claims, DateTime.UtcNow.AddMinutes(10));
An existing token can be decoded using the method Decode()
.
var jsongWebToken = new JsonWebToken();
TokenInformation tokenInfo = jsongWebToken.Decode(token);
The TokenInformation
class exposes four main properties: Header
, Claims
, ExpiresOn
and HasExpired
. If the key
is provided, the Decode
method will also validate the signature throwing an InvalidSignatureException
if the validation fails.
try
{
var key = Encoding.UTF8.GetBytes("secret");
var jsongWebToken = new JsonWebToken();
jsongWebToken.Decode(token, key);
}
catch (InvalidSignatureException ex)
{
Console.WriteLine($"Invalid {ex.InvalidSignature}, expected {ex.ExpectedSignature}.");
}