Skip to main content

JWT Tokens

What is JWT?

"Signed, not encrypted. Stateless auth token."

JWT (JSON Web Token) is a self-contained, signed token used for authentication and authorization.

"JWT is a stateless authentication mechanism where the server issues a signed token that the client sends with each request."


JWT Structure

Header.Payload.Signature

xxxxx.yyyyy.zzzzz

① Header

  • Algorithm (alg)
  • Token type (JWT)
{ "alg": "HS256", "typ": "JWT" }

② Payload

  • Registered: iss, sub, exp
  • Custom: userId, role

⚠️ Readable, not secret

③ Signature

  • Ensures integrity
  • Prevents tampering

"The signature is created by hashing the header and payload together with a secret key (using algorithms like HMACSHA256). If anyone changes any part of the header or payload, the signature will no longer match when the server checks it. This ensures that the token's data can't be tampered with—if the signature doesn't validate, the server rejects the token."


JWT Is NOT Encrypted

"Anyone can read it, only server can trust it."

  • Base64Url ≠ encryption
  • Payload can be decoded by anyone
  • Security comes from signature verification

"JWT payload is readable, so sensitive data should never be stored in it."


How JWT Is Created

Encode → Sign → Return

  1. Create claims
  2. Base64Url encode header + payload
  3. Sign using secret/private key
  4. Return token to client
Signature = HMACSHA256(
base64(header) + "." + base64(payload),
secret
)

How JWT Is Validated (Server Side)

Verify signature → Validate claims

Server checks:

  • ✅ Signature matches
  • exp not expired
  • iss and aud valid

❌ No DB lookup needed (stateless)

"JWT validation recreates the signature and compares it with the incoming token."


Where JWT Is Sent

Authorization header

Authorization: Bearer <JWT>
  • Sent on every request
  • Server extracts claims → creates ClaimsPrincipal

HS256 vs RS256 (Very Common Question)

Shared secret vs key pair

AlgorithmTypeNotes
HS256SymmetricSame secret signs & verifies
RS256AsymmetricPrivate key signs, public key verifies

"RS256 is better for microservices because verification doesn't require sharing secrets."


Why JWT Is Stateless (Key Benefit)

No session store

  • Server stores no session
  • Token contains all required info
  • Easy to scale horizontally

"JWT scales well because the server doesn't maintain session state."


JWT Authentication in ASP.NET Core (Conceptual Flow)

Middleware validates token

  1. Client sends JWT
  2. JwtBearerMiddleware runs
  3. Token validated
  4. Claims attached to HttpContext.User
  5. [Authorize] checks claims/roles

Authorization with JWT

Authentication

[Authorize];

Role-based

[Authorize((Roles = "Admin"))];

JWT must include:

"role": "Admin"

JWT Expiration (Security Critical)

Short-lived tokens

  • exp claim required
  • Typical: 15–30 minutes
  • Expired token → 401

"JWTs should always be short-lived."


Refresh Tokens (Must Know)

JWT = short, Refresh = long

  • JWT → access API
  • Refresh token → get new JWT
  • Stored server-side
  • Can be revoked

"Refresh tokens solve JWT's non-revocable nature."


JWT Revocation Problem

JWT can't be revoked by default

Solutions:

  • Short expiration
  • Refresh token rotation
  • Token blacklist (Redis)

Where to Store JWT (Security Question)

XSS vs CSRF trade-off

StorageRisk
localStorage❌ XSS
sessionStorage❌ XSS
HTTP-only cookie✅ safer

"HTTP-only cookies are safer against XSS."


Common JWT Mistakes (Interview Gold)

❌ Storing sensitive data in payload ❌ Long expiration times ❌ Weak secret key ❌ Not validating issuer/audience ❌ Using HTTP instead of HTTPS


"JWT is a stateless authentication mechanism where the server issues a signed token containing user claims. The token consists of a header, payload, and signature. The signature ensures integrity, while claims like exp, iss, and roles are validated on each request. Since JWTs are stateless, they scale well, but they can't be revoked easily, so we use short expiration times and refresh tokens for long-lived sessions."


🧠 Ultra-Compact Cheat Sheet

JWT = Header.Payload.Signature
Readable, not encrypted
Signed = integrity
Stateless = scalable
HS256 = shared secret
RS256 = key pair
exp required
Bearer token
Short JWT + Refresh token