Whilst building an API in .Net Core 3.1 recently I needed to decode a JWT token that we received from an authentication service. Here is a step by step guide explaining how to decode the JWT token in a .Net core application, in C#.
- Install the System.IdentityModel.Tokens.Jwt Nuget Package
- Add using directive to C# file
- Read the decoded JWT token
- Access the token expiry date
Install 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 using directive to file
Then add the using directive to the top of your page like this:
using System.IdentityModel.Tokens.Jwt;
Decode the JWT token
You can check the information stored in your JWT token by using this website. You paste your encoded JWT token string into the textbox and it will show you your decoded payload. This code is the simplest example of how to decode the token:
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.
How to get 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.
Summary
This post has given you an example of how to read the encoded data in a JWT token including reading the expiry date of the token.