Notes › Web Development
Authentication — JWT, Sessions and Cookies
- Authentication = who are you? (logging in)
- Authorization = what are you allowed to do? (admin-only routes, owning a post)
Never store plain passwords
Store a hash made with a slow, salted algorithm — bcrypt or argon2. A salt (random value per password) means two users with the same password get different hashes.
import bcrypt from "bcryptjs";
const hash = await bcrypt.hash(plainPassword, 10); // 10 = cost factor
const ok = await bcrypt.compare(loginPassword, hash); // true / false
Never use plain SHA-256/MD5 for passwords — they are too fast to brute-force.
Option 1: sessions (stateful)
- User logs in → the server creates a session (stored in memory, Redis or the DB) and sends its id in a cookie.
- The browser sends the cookie automatically on every request.
- The server looks up the session to know the user.
- ✅ Easy to log a user out everywhere (delete the session).
- ❌ The server must store sessions; scaling needs a shared store.
Option 2: JWT (stateless)
A JSON Web Token is a signed string: header.payload.signature.
eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEyMyIsImV4cCI6MTcyOH0.Xg3k…
header payload (base64, NOT encrypted) signature
The server signs the payload with a secret; later it verifies the signature to trust the payload without a database lookup.
import jwt from "jsonwebtoken";
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "7d" });
// middleware
function protect(req, res, next) {
const header = req.headers.authorization || ""; // "Bearer <token>"
const token = header.startsWith("Bearer ") ? header.slice(7) : null;
if (!token) return res.status(401).json({ message: "Not logged in" });
try {
const { id } = jwt.verify(token, process.env.JWT_SECRET);
req.userId = id;
next();
} catch {
res.status(401).json({ message: "Session expired, please log in again" });
}
}
- ✅ No server-side storage; works across many servers and mobile apps.
- ❌ Hard to revoke before it expires → keep access tokens short-lived and use refresh tokens, or a token version on the user.
- ⚠️ The payload is only base64 — never put secrets in it.
Sessions vs JWT
| Session | JWT | |
|---|---|---|
| State on server | yes | no |
| Logout / revoke | easy | needs extra work |
| Scaling | shared session store | easy |
| Best for | classic server-rendered sites | SPAs, mobile, many services |
Where to keep the token in the browser
| Storage | XSS can steal it? | Sent automatically (CSRF risk)? |
|---|---|---|
localStorage |
✅ yes | ❌ no |
| httpOnly cookie | ❌ no (JS can't read it) | ✅ yes → use SameSite + CSRF protection |
Cookie flags: httpOnly (no JS access), Secure (HTTPS only), SameSite=Lax/Strict (blocks most CSRF), Max-Age.
Protecting routes
Backend: check the token on every protected API route and check roles/ownership:
const adminOnly = (req, res, next) => (req.user.role === "admin" ? next() : res.status(403).json({ message: "Admins only" }));
Frontend (React): hide pages for logged-out users, but remember this is only for UX — the server must enforce permissions.
OAuth / "Sign in with Google"
The user signs in on Google; Google gives your app a token proving who they are; your server verifies it with Google and creates its own session/JWT. You never see the user's Google password.
Other must-haves
- Email verification and password reset with random, single-use, expiring tokens (store only their hash).
- Rate limit login and OTP endpoints to stop brute force.
- Same error for "wrong email" and "wrong password" (don't reveal which accounts exist).
- HTTPS everywhere; secrets in environment variables; rotate the JWT secret if it leaks.
Common security bugs
| Bug | Fix |
|---|---|
| Plain or MD5 passwords | bcrypt/argon2 |
| JWT secret in code / weak secret | long random secret in env |
Trusting role sent by the client |
read it from the DB/token on the server |
| No expiry on tokens | expiresIn + refresh flow |
| XSS stealing tokens | escape output, CSP, httpOnly cookies |
IDOR (/api/orders/123 of another user) |
check ownership on every request |
Interview one-liners
- 401 = not authenticated, 403 = authenticated but not allowed.
- JWT is signed, not encrypted.
- Hash + salt passwords with a slow algorithm.
- Authorization must always happen on the server.
- Related: Node.js and Express, HTTP vs HTTPS.