Introduction
There are plenty of materials on how to manage JWT tokens in C# environment.
But I found most of them are either too complicated for the beginner or outdated.
In this example, we will create and read a JWT token using a simple console app, so we can get a basic idea of how we can use it in any type of projects.
Let's create a simple console project and add these libraries as references:
System.IdentityModel;
System.Security
Next, we will need JWT Tokens Package.
Nuget install-package "System.IdentityModel.Tokens.Jwt"
Now we are ready to play with JWT Tokens:
static void Main(string[] args)
{
Console.WriteLine("");
string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b372742
9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
var securityKey = new Microsoft
.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(secToken);
Console.WriteLine(tokenString);
Console.WriteLine("Consume Token");
var token = handler.ReadJwtToken(tokenString);
Console.WriteLine(token.Payload.First().Value);
Console.ReadLine();
}