Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode JWT tokens in .Net 4.0 based Application

Tags:

c#

.net

jwt

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?

like image 650
Neha Avatar asked Dec 03 '18 11:12

Neha


1 Answers

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");
}
like image 189
Anurag R Avatar answered Sep 19 '22 15:09

Anurag R