Home » C# » How to decode a JWT token in a .Net Core API using C#

How to decode a JWT token in a .Net Core API using C#

By Emily

Whilst building an API in .Net Core 3.1 using C# recently, I needed to decode a JWT token that we received from an authentication service. This post is a step-by-step guide that explains how to read and get data from the JWT token using C# in a .Net Core application. In other words, how to ‘jwt token decode’. I’ll show you how to decode the contents of the token so that you can read the information stored within it.

Although they are commonly referred to as JWT tokens, the ‘T’ of ‘JWT’ stands for token. So it doesn’t really make sense to call them JWT tokens, but everybody does 🙂 It actually stands for JSON web token – using an open standard these provide a self-contained secure way to pass information as an object between applications.

Install the System.IdentityModel.Tokens.Jwt Nuget Package

To install the Nuget package navigate to the Nuget package manager in Visual Studio and search for the package by name – System.IdentityModel.Tokens.Jwt. Alternatively, if you prefer using the command line, type this in the NET Core CLI: 

dotnet add package System.IdentityModel.Tokens.Jwt

Add Tokens.Jwt using directive to file

Open the page from which you will be decoding the JWT token. Then add this using directive to the top of the page like this:

using System.IdentityModel.Tokens.Jwt;

Decode the JWT token using C#

Using the jwt.io website, you can check the information stored in your JWT token. You paste your encoded JWT token string into the textbox and it will show you your decoded payload.

jwt decode token example

This code is the simplest example of how to decode the token in C# :

var token = new JwtSecurityToken(jwtEncodedString: idtoken);

If you debug your code and examine the token itself, you’ll see it has many properties. The one you want to focus on is called “Claims”, which is a collection of properties containing the information you are going to want access to.

Find the JWT token expiry date

public string GetIdTokenExpiry(string idtoken)
{
  var token = new JwtSecurityToken(jwtEncodedString: idtoken);
  string expiry = token.Claims.First(c => c.Type == "expiry").Value;
  return expiry;
}

Please note that the string “expiry” may be different in your token so you may have to edit that text for the code to work.

Summary

This post has given you an example of how to read the encoded data in a JWT token in C#. I’ve also explained how to read the expiry date of the token.

Related