DrillLab
第 97 / 105 道97 / 105 · #361

session vs cookie

sessions vs cookies

先自己答,再往下看Answer it yourself first

先纠正一个常见混淆:它们不是同级的东西。cookie 是「浏览器存小数据的机制」session 是「服务器记住用户状态的方案」—— 而 session 通常靠 cookie 来传那个 id

CookieSession
存在哪浏览器服务器(内存 / Redis / 数据库)
存什么小字符串(≤ 4 KB)任意大小的用户数据
安全性用户能看能改用户只拿到一个 id
能否主动失效要等过期或被覆盖能,删掉服务端记录就行

典型流程:登录成功 → 服务器建 session、 生成 session id → 通过 Set-Cookie 发给浏览器 → 之后每个请求浏览器自动带上 → 服务器用 id 查出用户。

Cookie 的四个安全属性必须会:

  • HttpOnly—— JS 读不到,防 XSS 偷 cookie
  • Secure—— 只在 HTTPS 下发送
  • SameSite——Strict / Lax /None防 CSRF的主要手段
  • Max-Age / Domain /Path—— 作用范围

会追问:「session vs JWT 怎么选?」——

  • 要能立刻踢人下线(后台管理、支付类)→ session
  • 多服务、跨域、 移动端 + Web 共用JWT(配 refresh token)

还会问:「session 在多实例部署下怎么办?」—— 存内存会导致「刷新一下就掉登录」 (请求打到别的实例)。 解法是把 session 存 Redis, 或者用粘性会话(不推荐)。

First, clear up the usual confusion: these are not two options at the same level. A cookie is a browser mechanism for storing a small value; a session is a server-side way of remembering who the user is — and a session normally uses a cookie to carry its id.

CookieSession
Lives whereThe browserThe server (memory / Redis / database)
Holds whatA small string, 4 KB or lessUser data of any size
SecurityThe user can read it and change itThe user only ever holds an id
Can you revoke it?Only by expiry or overwriteYes — delete the server-side record

The typical flow: login succeeds → the server creates a session and a session id → it goes out via Set-Cookie → the browser attaches it to every subsequent request → the server looks the user up by that id.

You have to know the four cookie security attributes:

  • HttpOnly — JS cannot read it, which stops XSS from stealing the cookie
  • Secure — only sent over HTTPS
  • SameSite Strict / Lax / None, the main defence against CSRF
  • Max-Age / Domain / Path — its scope

Follow-up: “Session or JWT?” —

  • You need to kick someone out right now (admin panels, anything touching payments) → session
  • Many services, cross-domain, one API for both mobile and web JWT, with a refresh token

They will also ask: “What happens to sessions across several instances?” — keeping them in memory means “refresh the page and I am logged out” when the request lands on a different instance. The fix is to put sessions in Redis, or sticky sessions (not recommended).