How to create a JWT token from a secret


This post shows few ways of creating JWT token from a secret.

1. Creating it online

You can use https://jwt.io/ to create a token. As shown in following image you can add the secret to green-box and payload to blue-box and you can get your token in the red-box

2. Creating using NodeJS

Install the following dependency

npm install jsonwebtoken

Then use the following code to create a token

const jwt = require('jsonwebtoken');

const payload = { foo: 'bar' };
const secretKey = 'your_secret_key';

const token = jwt.sign(payload, secretKey);
console.log('JWT Token:', token);

3. Creating using C#

To create a JWT token in C#, you can use the System.IdentityModel.Tokens.Jwt library. If you don't have it installed, you can use NuGet Package Manager Console to install it:

Install-Package System.IdentityModel.Tokens.Jwt
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

class Program
{
    static void Main()
    {
        // Your payload data
        var payload = new[]
        {
            new Claim("foo", "bar"),
        };

        // Your secret key
        var secretKey = "your_secret_key";

        // Create symmetric security key from the secret
        var securityKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(secretKey));

        // Create credentials with the above key algorithm
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        // Create a JWT token
        var token = new JwtSecurityToken(
            claims: payload,
            expires: DateTime.UtcNow.AddHours(1), // Token expiration time
            signingCredentials: credentials
        );

        // Write the token to the console
        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenString = tokenHandler.WriteToken(token);
        Console.WriteLine("JWT Token: " + tokenString);
    }
}