using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
public static void Main()
String secretKey = "SECRETKEY_IS_VERY_LONGGGGGGGGGGGGGGGGGGGGGGGG";
String userId = "xxxxxxxx";
String token = genToken(userId,secretKey);
Console.WriteLine(token);
var json = ValidateJwtTokenToJson(token,secretKey);
public static String genToken(String userId,String secretKey) {
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SECRETKEY_IS_VERY_LONGGGGGGGGGGGGGGGGGGGGGGGG"));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
new Claim("userId", userId),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
var token = new JwtSecurityToken(
expires: DateTime.UtcNow.AddMinutes(expireMinutes),
signingCredentials: credentials
return new JwtSecurityTokenHandler().WriteToken(token);
public static string? ValidateJwtTokenToJson(string token, string secretKey)
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(secretKey);
var validationParameters = new TokenValidationParameters
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
if (validatedToken is JwtSecurityToken jwtToken &&
jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
var claimsDict = new Dictionary<string, string>();
foreach (var claim in principal.Claims)
claimsDict[claim.Type] = claim.Value;
return JsonSerializer.Serialize(claimsDict, new JsonSerializerOptions { WriteIndented = true });