跳到主要内容

JWT Tokens

What is JWT? (One-liner)

🧠 Memory hook

"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 (Must Memorize)

🧠 Memory hook

Header.Payload.Signature

xxxxx.yyyyy.zzzzz

① Header

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

② Payload (Claims)

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

⚠️ Readable, not secret

③ Signature

  • Ensures integrity
  • Prevents tampering

"The signature guarantees the token hasn't been modified."


JWT Is NOT Encrypted ❗ (Very Important)

🧠 Memory hook

"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 (Internal Flow)

🧠 Memory hook

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)

🧠 Memory hook

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

🧠 Memory hook

Authorization header

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

HS256 vs RS256 (Very Common Question)

🧠 Memory hook

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)

🧠 Memory hook

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."


9️⃣ JWT Authentication in ASP.NET Core (Conceptual Flow)

🧠 Memory hook

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)

🧠 Memory hook

Short-lived tokens

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

"JWTs should always be short-lived."


Refresh Tokens (Must Know)

🧠 Memory hook

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

🧠 Memory hook

JWT can't be revoked by default

Solutions:

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

Where to Store JWT (Security Question)

🧠 Memory hook

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


(Polished)

"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