Hi Geeks,
I just want to post a small post related to JWT code. Recently, when I was analyzing a web that use JWT to maintain its authentication and authorization, I found that having a good small code to generate your JWT token will help you to automate the token generation.
Below is small C# code to generate JWT token
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class Generate
{
public static void Main(String[] args)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("SecretMessageFromRio");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "1")
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token); Console.WriteLine(jwt);
}
}
You can use the code above and change the token secret keys with your own key.