session vs cookie
sessions vs cookies
先纠正一个常见混淆:它们不是同级的东西。cookie 是「浏览器存小数据的机制」,session 是「服务器记住用户状态的方案」—— 而 session 通常靠 cookie 来传那个 id。
| Cookie | Session | |
|---|---|---|
| 存在哪 | 浏览器 | 服务器(内存 / Redis / 数据库) |
| 存什么 | 小字符串(≤ 4 KB) | 任意大小的用户数据 |
| 安全性 | 用户能看能改 | 用户只拿到一个 id |
| 能否主动失效 | 要等过期或被覆盖 | 能,删掉服务端记录就行 |
典型流程:登录成功 → 服务器建 session、 生成 session id → 通过 Set-Cookie 发给浏览器 → 之后每个请求浏览器自动带上 → 服务器用 id 查出用户。
Cookie 的四个安全属性必须会:
HttpOnly—— JS 读不到,防 XSS 偷 cookieSecure—— 只在 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.
| Cookie | Session | |
|---|---|---|
| Lives where | The browser | The server (memory / Redis / database) |
| Holds what | A small string, 4 KB or less | User data of any size |
| Security | The user can read it and change it | The user only ever holds an id |
| Can you revoke it? | Only by expiry or overwrite | Yes — 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 cookieSecure— only sent over HTTPSSameSite—Strict/Lax/None, the main defence against CSRFMax-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).