Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › Web Development

Authentication — JWT, Sessions and Cookies

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)

  1. User logs in → the server creates a session (stored in memory, Redis or the DB) and sends its id in a cookie.
  2. The browser sends the cookie automatically on every request.
  3. The server looks up the session to know the user.

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" });
  }
}

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

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

More Web Development notes