Lesson 20 / 25

Sessions and Tokens

Cookies, JWTs and expiry.

Protect the proof of login

After login, a session cookie or token proves identity, so it must be protected: generate session IDs with a secure random source, regenerate them at login (prevents session fixation), set cookies Secure, HttpOnly and SameSite, expire sessions after inactivity and on logout, and invalidate them on password change. With JWTs, verify the signature with an explicit algorithm allow-list (never accept alg: none), check exp, aud and iss, keep lifetimes short with refresh tokens, and avoid storing long-lived tokens in localStorage where XSS can read them.

Verifying a JWT strictly

Python with the PyJWT library (a sketch).

import jwt

claims = jwt.decode(
    token,
    key=PUBLIC_KEY,
    algorithms=["RS256"],              # explicit allow-list
    audience="https://api.example.com",
    issuer="https://login.example.com/",
    options={"require": ["exp", "iat", "sub"]},
)
user_id = claims["sub"]

Log out must work server-side

Invalidate the server-side session or revoke the refresh token; deleting a cookie in the browser alone is not enough.

Quick check: Why regenerate the session ID at login?

  • To make cookies smaller
  • To prevent session fixation, where an attacker sets a known session ID beforehand
  • To improve caching
  • To log the user out
Answer

To prevent session fixation, where an attacker sets a known session ID beforehand — New privilege level, new session.