SECURITY ENGINEERING · PART 8 · WRITING SECURE CODE · AUTH · 114 OF 229

Sessions vs Tokens: Designing Authentication

Authentication is proving who you are, and it is where many breaches begin. This episode covers designing it: the three factors and MFA, server-side sessions versus stateless tokens and when to use each, how session cookies and JWTs should be configured, secure login, logout and password reset flows, account recovery as the weakest link, and the rule to not build your own identity system when a good one exists.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • MFA always
  • sessions for revocation, JWTs for scale
  • strict cookies and tokens
  • strong recovery
  • reuse identity

Notes

Factors and MFA

Factors come in three kinds: something you know like a password, something you have like a phone or security key, and something you are like a fingerprint. Multi-factor means two different kinds, not two passwords. The strongest are phishing-resistant: passkeys and hardware keys, in episode twelve. SMS codes beat nothing but can be phished, so prefer app codes or passkeys. MFA is the highest-value control against stolen passwords.

The factors
  • knowledge: password, PIN
  • possession: phone, security key, authenticator app
  • inherence: fingerprint, face
  • MFA = two different factors, not two passwords
  • strongest: a phishing- resistant factor (passkey, security key)
  • SMS codes: better than nothing, but phishable

Server-side sessions

There are two models. The classic one is server-side sessions. On login the server stores the state and hands the client a random session identifier in a cookie. Each request, the server looks it up. The advantage is control: logout and revocation are instant, because you delete the session server-side. The cost is that the server, or a shared cache like Redis, holds the state. For most web apps this is the right default, and simpler to reason about than tokens.

Session model
  • on login, server stores session state, gives the client a random session ID in a cookie
  • each request: server looks up the ID
  • logout and revocation are instant: delete server-side
  • state lives server-side (store or cache)
  • great default for web apps

Stateless tokens

The other model is stateless tokens, usually JWTs. On login the server issues a signed token containing claims about the user, and the client sends it on each request. The server verifies the signature without any lookup, which scales nicely across many services and APIs with no shared session store. The cost is revocation: a valid token works until it expires, so you cannot instantly log someone out. The standard answer is a short-lived access token plus a longer-lived refresh token you can revoke.

Token model (JWT)
  • on login, server issues a signed token (JWT) with claims; client sends it back
  • server verifies the signature, no lookup needed
  • scales across services without shared session state
  • cost: hard to revoke before expiry
  • fix: short-lived access + refresh token

Configure them right

Either model fails if handled badly. A session cookie must be HttpOnly so scripts cannot read it, Secure so it only goes over HTTPS, and SameSite to limit cross-site sending, with a random identifier of at least 128 bits, rotated on login to prevent fixation. A JWT must have its signature and algorithm verified, the algorithm pinned and none rejected, and its expiry, issuer and audience checked. And mind where a token is stored, because script storage is readable by any cross-site scripting bug.

Secure handling
  • session cookie: HttpOnly, Secure, SameSite, sensible expiry, random 128-bit ID
  • rotate the session ID on login (prevents fixation)
  • JWT: verify signature AND alg; check exp, iss, aud; short lifetime
  • store tokens carefully; avoid localStorage for sensitive apps (XSS steals it)

The flows

The flows need as much care as the mechanism. Login should rate-limit and lock out repeated failures, and return an identical response for a wrong username and a wrong password, so it does not reveal which accounts exist. Check passwords against breached lists. Logout must destroy the server session or revoke the token, not just redirect. Enforce idle and absolute timeouts. And require step-up auth, re-entering a password or MFA, before sensitive actions like changing an email or making a payment.

Login and logout
  • login: rate-limit, lockout, identical response for bad user vs bad password
  • breached-password check
  • logout: destroy session or revoke the token
  • idle and absolute timeouts
  • step-up auth for sensitive actions (password or MFA)

Account recovery

Account recovery is often the weakest link, because a reset flow that bypasses MFA undoes your login security. Do it properly: email a single-use token that expires within about fifteen minutes, long and random, and store only its hash so a database leak does not expose live tokens. Do not reveal whether an email has an account. Invalidate sessions when the password changes. And recovery should be as strong as login; if an attacker resets a password with just an email, MFA bought you little.

Password reset done right
  • email a single-use token that expires quickly (15 min)
  • random and long; store only its hash
  • do not reveal whether an email exists
  • invalidate sessions on reset
  • recovery as strong as login: keep MFA where possible
  • rate-limit reset requests

Do not build your own

The last principle is the most practical: do not build your own identity system unless identity is your product. It has countless edge cases, MFA, recovery, lockout, federation, auditing, each a chance to get it wrong. Use a mature identity provider such as Okta, Entra, Cognito or self-hosted Keycloak, or a vetted framework like Spring Security, and build only what is unique to your app. Never store passwords in plaintext or invent your own token crypto.

Buy vs build
  • identity has countless edge cases: MFA, recovery, lockout, federation, audit
  • use a provider (Okta, Entra, Cognito, Keycloak) or a vetted framework
  • build only what is unique to you
  • never store plaintext passwords or roll your own crypto

Common mistakes

Mistakes. Passwords only, no MFA. A session identifier not rotated on login, allowing fixation. A JWT accepted with the algorithm none or an unverified signature. No real logout or revocation. A reset flow that bypasses MFA or reveals which emails have accounts. Tokens in script-readable storage in apps prone to cross-site scripting. And a whole identity system built from scratch when a proven one exists. Each turns up regularly in real assessments.

Avoid these
  • passwords only, no MFA
  • session ID not rotated on login (fixation)
  • JWT alg:none or unverified signature
  • no real logout/revocation
  • reset bypasses MFA or reveals accounts
  • tokens in localStorage in XSS-prone apps
  • home-made identity

Say it like this

In the interview: for a web app I default to server-side sessions, because revocation is instant, with an HttpOnly, Secure, SameSite cookie, rotated on login. For stateless APIs I use JWTs, with short-lived access tokens, revocable refresh tokens, and strict checks of the algorithm and the expiry, issuer and audience claims. I require MFA, build a recovery flow that does not bypass it, and use a proven identity provider rather than my own. Passwords are hashed with Argon2 or bcrypt.

In the interview
  • "Server sessions for web apps: instant revocation, HttpOnly
  • Secure SameSite cookie, rotated on login. JWTs for stateless APIs: short-lived
  • access plus revocable refresh, verified alg and claims. MFA
  • everywhere, strong recovery, and a proven identity
  • provider rather than my own."

Interview questions

Q1What is the difference between authentication and authorization?

Authentication verifies who a user is, for example by password and a second factor. Authorization decides what an authenticated user is allowed to do. Authentication comes first, and both must be enforced on the server for every request.

Q2What is multi-factor authentication?

Requiring two or more different kinds of factor: knowledge (password), possession (phone or security key) or inherence (biometric). Two passwords are not MFA. Phishing-resistant factors such as passkeys and hardware keys are the strongest.

Q3What is the difference between server-side sessions and JWTs?

With sessions the server stores state and the client holds an opaque ID, so revocation is instant but state must be stored. With JWTs the client holds a signed token the server verifies without lookup, which scales statelessly but is hard to revoke before expiry.

Q4How should a session cookie be configured?

With HttpOnly to block script access, Secure to require HTTPS, an appropriate SameSite value, a cryptographically random identifier of at least 128 bits, sensible idle and absolute timeouts, and rotation of the identifier on login to prevent session fixation.

Q5How do you revoke a JWT before it expires?

Pure stateless JWTs cannot be revoked directly, so use short-lived access tokens with a longer-lived refresh token that can be revoked, and optionally maintain a server-side denylist or token version. Keeping access-token lifetimes short limits the exposure window.

Q6Why is the password reset flow a common weak point?

Because it can bypass the protections on login. If reset tokens are long-lived, guessable, stored in plaintext, or the flow skips MFA or reveals account existence, an attacker can take over accounts without ever knowing the password.

Q7Why should you avoid building your own authentication system?

Identity has many subtle edge cases, MFA, recovery, lockout, federation and auditing, each easy to get wrong. Proven identity providers and vetted frameworks encode secure handling, so reusing them is more secure than reimplementing it.

Q8Should JWTs be stored in localStorage?

For sensitive applications it is risky, because any cross-site scripting flaw can read localStorage and steal the token. HttpOnly cookies, which scripts cannot read, are safer for browser clients, combined with CSRF defences appropriate to the setup.