I'm working on a project which is based on .Net 4.0 Framework and implementing ASP.NET Web APIs. My requirement is to decode JWT tokens coming to API. I was exploring "using System.IdentityModel.Tokens.JWT" but seems this is compatible with .Net 4.5 only. How do I access to JWT functions in my project which is based on .Net framework 4.0?
I was working on a .net 4 project, found JWT-Dotnet helpful. Here are the docs.
Can be installed easily using nuget. Details on NUGET can be found here
Install-Package JWT -Version 7.3.1
It supports .net from 3.5 onward. Decoding token is pretty easy. Below is a sample from documentation.
const string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s";
const string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
try
{
    IJsonSerializer serializer = new JsonNetSerializer();
    var provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
    
    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");
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With