Sikau

Security · Day 10 · about 40 min

Sessions and cookies

Random session ids, expiry, rotation after login, and safe cookie flags.

The id is the key to the house

After login, the browser must prove who it is on every request. The common way is a session: the server stores who you are, and the browser carries only a random id in a cookie. Whoever holds that id is you, so the id needs the same care as a password.

If an attacker guesses, steals or fixes a learner's session id, they skip the login completely. Three habits close most of these doors: unpredictable ids, short lifetimes, and a new id at every change of privilege.

What makes a good session

A session id must be long and random: 128 bits from the secure random generator, so guessing is hopeless. Never build it from a counter, a timestamp or the user's email. The server keeps the data (user, expiry) and the cookie holds only the id, so nothing sensitive sits in the browser.

Give every session an expiry. An idle timeout (say 30 minutes without activity) ends forgotten laptops, and an absolute limit (say 7 days) bounds the damage of a stolen id. Logging out must destroy the session on the server; deleting the cookie alone leaves a valid id alive.

function createSessions({ ttl = 3600 } = {}) {
  const store = new Map(); // id -> { userId, expires }
  const newId = () => [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");

  function create(userId, now) {
    const id = newId();
    store.set(id, { userId, expires: now + ttl });
    return id;
  }
  function get(id, now) {
    const s = store.get(id);
    if (!s) return null;
    if (now >= s.expires) {
      store.delete(id);
      return null;
    }
    return s.userId;
  }
  function rotate(id, now) {
    const userId = get(id, now);
    if (userId === null) return null;
    store.delete(id);
    return create(userId, now);
  }
  function destroy(id) {
    store.delete(id);
  }
  return { create, get, rotate, destroy };
}

The rest of this lesson

  • Rotation and cookie flagsexplain
  • After rotationpredict
  • Cookie flagsfill
  • A session's lifeorder
  • A session storewrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browserright here

Continue with Google

See all 12 lessons of Security