JWT Tokens

Below the basic operations to create and validate JWT tokens

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

public class JwtGenerator
{
    public static string GenerateSecureKey()
    {
        using var randomNumberGenerator = RandomNumberGenerator.Create();
        var key = new byte[32]; // 256 bits
        randomNumberGenerator.GetBytes(key);
        return Convert.ToBase64String(key);
    }

    public static string GenerateToken(string secret)
    {
        JwtSecurityTokenHandler tokenHandler = new();
        byte[] key = Encoding.ASCII.GetBytes(secret);

        SecurityTokenDescriptor tokenDescriptor = new()
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                // Add any claims you need here
                new Claim(ClaimTypes.Name, "username"),
            }),
            Expires = DateTime.UtcNow.AddMinutes(60),
            SigningCredentials = 
                new SigningCredentials(
                        new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

    public static ClaimsPrincipal DecodeAndValidateToken(string token, string key)
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)),
            ValidateIssuer = false,
            ValidateAudience = false,
            ClockSkew = TimeSpan.Zero
        };

        var tokenHandler = new JwtSecurityTokenHandler();

        try
        {
            var claimsPrincipal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var validatedToken);
            return claimsPrincipal;
        }
        catch (SecurityTokenException)
        {
            Console.WriteLine("Invalid token.");
            return null;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
            return null;
        }
    }

    public static void Main()
    {
        string key = GenerateSecureKey();
        Console.WriteLine(key);

        Console.WriteLine();

        string token = GenerateToken(key);
        Console.WriteLine(token);

        var claimsPrincipal = DecodeAndValidateToken(token, key);
        foreach (var claim in claimsPrincipal.Claims)
        {
            Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
        }
    }
}

Share

Leave a Reply

Your email address will not be published. Required fields are marked *