CodePark/ questions / Sessions vs tokens
START PRACTICINGPRACTICE
Backend question · Auth & security › Sessions vs tokens

What properties should a session id have, and what lifecycle rules should a secure session implementation follow?

A session id must be random, long and meaningless. It must also be issued, renewed and ended by clear rules.

Properties of the id:

  • Make it with a cryptographically secure random generator (CSPRNG: a random generator whose output an attacker can't predict).
  • Give it enough entropy (randomness) that guessing it is not possible in practice. OWASP asks for at least 64 bits.
  • Make it meaningless. Don't put user ids or timestamps inside it.
  • Use a generic cookie name, so the name doesn't tell attackers which framework you use.

Lifecycle rules:

  • Create a new id at login and when the user's privileges change. This stops session fixation, where an attacker makes the victim use an id the attacker already knows.
  • Enforce an idle timeout (the session ends after a period with no activity). Also enforce an absolute timeout (the session ends after a fixed time, even if active).
  • At logout, invalidate the session on the server, not only in the browser.
  • After a password change or account recovery, end the user's other sessions.
  • Only accept ids that the server itself issued.

Transport:

  • Send the id only over HTTPS, in a cookie with the Secure and HttpOnly flags.
  • Never put it in URLs. URLs leak into logs, browser history and Referer headers.
  • Make the id with a CSPRNG, with at least 64 bits of entropy and no meaning inside it.
  • Create a new id at login and when privileges change.
  • Use idle and absolute timeouts, and invalidate the session on the server at logout.
  • End the user's other sessions after a password change.
  • Never put the id in URLs, and send it only over HTTPS.