๐ JWT: JSON Web Tokens Explained
How stateless authentication works โ from structure to security
What Is JWT?
JWT (JSON Web Token) is a compact, self-contained token format for securely transmitting information between parties. It consists of three Base64 URL-encoded parts separated by dots: header.payload.signature.
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Three Parts of JWT
1. Header
{"alg": "HS256", "typ": "JWT"}
2. Payload
Contains claims (data). Standard fields:
| Field | Meaning |
|---|---|
sub | Subject (user ID) |
iss | Issuer |
exp | Expiration (Unix timestamp) |
iat | Issued at |
โ Never put secrets in payload โ it's only Base64-encoded, not encrypted. Anyone can decode it.
3. Signature
Signature = HMAC-SHA256(header + "." + payload, secret). This proves the token wasn't tampered with.
JWT vs Session Auth
| Dimension | JWT | Session |
|---|---|---|
| Storage | Client-side | Server-side (Redis/DB) |
| Scalability | โ Stateless, microservice-friendly | โ Needs shared session store |
| Logout | โ Hard to invalidate immediately | โ Delete session |
Security Best Practices
- โ Set short expiry (15 min access token + 7 day refresh token)
- โ Always use HTTPS
- โ Validate all fields (exp, iss, aud)
- โ Never store passwords or secrets in payload
- โ Never put JWT in URL parameters
๐ Decode a JWT now
Header/Payload visualization, expiry check, client-side decoding
๐ Open JWT DecoderFAQ
Q: Is JWT encrypted?
No โ JWT is signed, not encrypted. Anyone can decode the payload. The signature only proves authenticity, not confidentiality. For encryption, use JWE.
Q: How to handle logout with JWT?
Maintain a token blacklist (Redis), or use short-lived access tokens with refresh tokens so logout is effectively handled by expiration.
๐ Related: SHA256 Hash โ ยท RSA Encryption โ ยท Base64 Encoder โ