Module 9 - Security

JWT & Tokens

Self-contained tokens that let servers verify identity without database lookups.

1The Concert Wristband Analogy

Simple Analogy
At a concert, you show ID once at the entrance and get a wristband. Security doesn't check your ID at every bar-they just see the wristband. A JWT is your wristband: it proves you were verified, contains info about you, and can't be faked (tamper-proof).

JWT (JSON Web Token) is a compact, URL-safe token containing claims (data) and a signature. The signature proves the token wasn't tampered with.

2JWT Structure

Three Parts (Base64 encoded, dot-separated)
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoiSm9obiJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Header

{"alg": "HS256", "typ": "JWT"}

Algorithm and token type

Payload

{"sub": "123456", "name": "John", "exp": 1699999999}

Claims: user data, expiration, issuer

Signature

HMACSHA256(header + '.' + payload, secret)

Verifies token wasn't modified

3Common Claims

ClaimNamePurpose
subSubjectUser ID
expExpirationWhen token expires (Unix timestamp)
iatIssued AtWhen token was created
issIssuerWho created the token
audAudienceIntended recipient

4JWT vs Session Tokens

JWT (Stateless)

Pros:
  • No server storage needed
  • Easy to scale (any server can verify)
  • Good for microservices
Cons:
  • Can't revoke before expiry
  • Larger than session IDs
  • Payload is readable (Base64)

Session Token (Stateful)

Pros:
  • Easy to revoke
  • Small token size
  • Server controls data
Cons:
  • Requires session store
  • Harder to scale
  • Extra DB lookup per request

JWTs shift storage from server to client. Great for scalability, but revocation requires extra work (blocklist).

5Security Best Practices

Use Short Expiration

Access tokens: 15 min to 1 hour. Use refresh tokens for longer sessions.

Validate Everything

Check signature, expiration, issuer, audience. Don't just decode.

Use Strong Secrets

For HS256, use 256+ bit random secret. Better: use RS256 with key pairs.

Don't Store Sensitive Data

Payload is Base64, not encrypted. Anyone can decode and read it.

Secure Storage

httpOnly cookies for web. Secure storage for mobile. Never localStorage.

6Revocation Strategies

Short Expiration

Token expires quickly. User re-authenticates. Simple but poor UX.

Token Blocklist

Store revoked token IDs in Redis. Check on each request. Adds state.

Token Versioning

Store version in user record. Increment to invalidate all tokens.

Refresh Token Rotation

Issue new refresh token each use. Detect stolen if old one is used.

7Key Takeaways

1JWT = Header.Payload.Signature - self-contained, verifiable token
2Stateless: server doesn't store sessions. Easy to scale.
3Payload is encoded, not encrypted. Don't store secrets.
4Short expiration + refresh tokens for security and UX.
5Always verify signature, exp, iss, aud. Never just decode.

?Quiz

1. JWT payload contains sensitive data. Is it safe?

2. How to immediately revoke a JWT?