using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
namespace JWTConsole
{
class Program
{
static void Main(string[] args)
{
var payload = new Dictionary<string, object>{
{ "claim1", 0 },
{ "claim2", "claim2-value" }
};
var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
Console.WriteLine(token);
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
try
{
//IDateTimeProvider provider = new UtcDateTimeProvider();
//IJwtValidator validator = new JwtValidator(serializer, provider);
//IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
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");
}
var now = provider.GetNow().AddMinutes(1);
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
payload = new Dictionary<string, object>{
{ "exp", secondsSinceEpoch }
};
token = encoder.Encode(payload, secret);
var json0 = decoder.Decode(token, secret,verify: true); // TokenExpiredException
Console.WriteLine(json0);
}
}
}
https://github.com/jwt-dotnet/jwt