Monday, 22 September 2025

JWT

🟢 1. What is JWT?

  • JWT stands for JSON Web Token.

  • It is a secure way to transmit information between a client (like a browser) and a server.

  • The information is digitally signed so it cannot be tampered with.

Analogy:

  • Think of JWT like a sealed envelope with a message inside.

  • Only the server can verify the seal (signature) to know it’s authentic.


🟢 2. Structure of JWT

A JWT is a string divided into 3 parts separated by dots (.):

Header.Payload.Signature
  1. Header – says what type of token it is and the algorithm used.

    { "alg": "HS256", "typ": "JWT" }
  2. Payload – the actual information (claims). Example:

    { "userId": 123, "email": "user@example.com", "role": "admin" }
  3. Signature – a hash created from header + payload + secret key.

    • Ensures the token is authentic and unchanged.


🟢 3. How JWT Works

  1. User logs in with username/password.

  2. Server verifies credentials.

  3. Server generates JWT (with user info in payload) and sends it to client.

  4. Client stores JWT (usually in local storage or cookies).

  5. For future requests, client sends JWT in HTTP header:

    Authorization: Bearer <token>
  6. Server verifies JWT signature. If valid, user is authenticated.


🟢 4. JWT in C# (.NET Core / .NET 5+)

Step 1: Install NuGet package

Install-Package System.IdentityModel.Tokens.Jwt

Step 2: Create a JWT

using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.Text; class Program { static void Main() { string secretKey = "my_super_secret_key_123!"; // keep it safe var key = Encoding.ASCII.GetBytes(secretKey); // 1. Create claims (user info) var claims = new[] { new Claim("userId", "123"), new Claim(ClaimTypes.Email, "user@example.com"), new Claim(ClaimTypes.Role, "Admin") }; // 2. Create token descriptor var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; // 3. Create token var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var jwt = tokenHandler.WriteToken(token); Console.WriteLine("JWT Token:"); Console.WriteLine(jwt); } }

Step 3: Validate JWT

var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(secretKey); var validationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero }; try { var principal = tokenHandler.ValidateToken(jwt, validationParameters, out var validatedToken); Console.WriteLine("Token is valid!"); Console.WriteLine("UserId: " + principal.FindFirst("userId")?.Value); } catch { Console.WriteLine("Invalid Token"); }

🟢 5. Important Points

  • Keep secret key safe! If leaked, attackers can create valid tokens.

  • Do not store sensitive info like passwords in the payload. JWT is only base64 encoded, not encrypted.

  • Expiration is important. Never issue a token without expiry.

  • Bearer token in HTTP header is standard.


🟢 Summary

  • JWT = Header + Payload + Signature

  • Used for authentication and authorization

  • Signed so server can trust it

  • In C#, use System.IdentityModel.Tokens.Jwt to create & verify tokens