TL;DR
A JWT (JSON Web Token) is a compact string that contains user information and is used for authentication. It has three parts: header, payload, and signature. The server creates a JWT after login and the client sends it with each request. JWTs are stateless (the server doesn't need to store them) but can't be revoked easily. Store them in httpOnly cookies, not localStorage. Keep expiration times short.
The Simple Explanation
When you log in, the server creates a token that says "this is user #123, they're an admin, and this token expires in 1 hour." The server signs this token so it can't be forged. You send this token with every request, and the server trusts it because only the server knows the signing key.
JWT Structure
A JWT looks like this: xxxxx.yyyyy.zzzzz
- Header: Algorithm and token type
- Payload: User data (claims)
- Signature: Verification that it wasn't tampered with
{ "sub": "user_123", "name": "Jane Doe", "role": "admin", "iat": 1706140800, "exp": 1706144400 }
Important: JWT payloads are only encoded, not encrypted. Anyone can decode and read them. Never put secrets or sensitive data in the payload.
JWT Security Best Practices
- Use strong secrets: At least 256 bits for HS256
- Set short expiration: 15 minutes to 1 hour for access tokens
- Store in httpOnly cookies: Protects against XSS
- Use refresh tokens: For getting new access tokens
- Validate everything: Check signature, expiration, issuer
Common JWT Mistakes
- Storing in localStorage (XSS vulnerable)
- Using weak signing secrets
- Setting expiration too long (days, weeks)
- Trusting the "alg" header without validation
- Not validating the signature on the server
Where should I store JWTs in the browser?
For security, store JWTs in httpOnly cookies rather than localStorage. localStorage is vulnerable to XSS attacks where malicious scripts can steal tokens. HttpOnly cookies cannot be accessed by JavaScript, protecting against XSS. If you must use localStorage, ensure strong XSS protections.
What is the difference between JWT and session-based authentication?
Sessions store user data on the server and give the client a session ID. JWTs are self-contained tokens that hold user data, so the server does not need to store session data. Sessions are easier to invalidate. JWTs are easier to scale but harder to revoke before expiration.
Why should I set short expiration times for JWTs?
JWTs cannot be invalidated once issued (without extra infrastructure). If a token is stolen, the attacker can use it until it expires. Short expiration times (15 minutes to 1 hour) limit the damage window. Use refresh tokens to get new access tokens without forcing users to log in again.