Skip to content

Cookie and 会话

理解 Cookie, 会话, and 如何 web apps keep 用户 logged in securely.

你将学到

  • 什么 Cookie 是 and 如何它们 travel 使用每个 HTTP 请求
  • 键 Cookie attributes: HttpOnly, Secure, SameSite, 最大值-Age
  • 如何服务器-边会话工作使用会话 ID Cookie
  • difference 之间 Cookie, localStorage, and JWTs

概念讲解

Cookies and Sessions

Cookies are small key-value pairs that the browser stores and automatically sends with every HTTP request to the matching domain. This automatic behavior is what makes cookies special — unlike localStorage, the server sees them on every request without any client-side code. Cookies are the foundation of authentication on the web: when you log in, the server sets a cookie, and every subsequent request includes it, proving who you are.

How Cookies Work

  1. The server sends a 设置-Cookie header in the HTTP response: 设置-Cookie: 会话=abc123; HttpOnly; Secure; SameSite=Strict.
  2. The browser stores the cookie.
  3. On every future request to that domain, the browser includes it: Cookie: 会话=abc123.
  4. The server reads the cookie, identifies the user, and responds accordingly.

Cookies have a size limit of about 4 KB each. They are sent on every request, so storing large data in cookies bloats every HTTP exchange.

Critical Cookie Attributes

  • HttpOnly — JavaScript cannot read the cookie (via document.Cookie). This prevents XSS attacks from stealing the cookie. Always set this on session cookies.
  • Secure — the cookie is only sent over HTTPS, never over plain HTTP. Essential for any sensitive cookie.
  • SameSite — controls when the cookie is sent on cross-site requests. Strict (never send cross-site), Lax (send on top-level navigations, the default), 无 (always send, requires Secure). This prevents CSRF attacks.
  • 最大值-Age or Expires — how long the cookie lives. Without this, the cookie is a "会话 Cookie" that clears when the browser closes.

0Server-Side Sessions

A session is server-side state identified by a session ID. The flow: the user logs in → the server creates a session in its database/memory → the server sends the session ID in an HttpOnly cookie → on each request, the server reads the cookie, looks up the session, and knows who the user is. The session data (user ID, roles, preferences) lives on the server; the cookie just holds the ID. This is more secure than storing all user data in the cookie itself.

Cookies vs. localStorage vs. JWTs

  • Cookies — sent automatically to the server. Best for session IDs with HttpOnly + Secure + SameSite.
  • localStorage — not sent to the server. Best for non-sensitive client-side preferences.
  • JWTs — self-contained tokens with signed claims. Can go in cookies (secure) or in Authorization headers (for APIs). If in localStorage, they are vulnerable to XSS.

For web apps (same origin), the most secure pattern is a server-side session with an HttpOnly cookie. For APIs consumed by third parties, JWTs in headers are common.

示例代码

              // Server-side: setting a secure session cookie (Node.js / Express)
app.post("/login", async (req, res) => {
  const user = await authenticate(req.body.email, req.body.password);
  if (!user) return res.status(401).json({ error: "Invalid credentials" });

  // Create a server-side session
  const sessionId = await createSession(user.id);

  // Set the cookie with all security attributes
  res.cookie("session", sessionId, {
    httpOnly: true,     // JS cannot read it — XSS-safe
    secure: true,       // HTTPS only
    sameSite: "strict", // CSRF protection
    maxAge: 86400000,   // 24 hours in ms
    path: "/"
  });

  res.json({ user: { id: user.id, name: user.name } });
});

// Client-side: reading a cookie (only non-HttpOnly ones!)
function getCookie(name) {
  const cookies = document.cookie.split("; ").reduce((acc, c) => {
    const [k, v] = c.split("=");
    acc[k] = v;
    return acc;
  }, {});
  return cookies[name];
}

// The session cookie is HttpOnly, so document.cookie
// does NOT include it — that is the point!
            

服务器创建会话 and 设置 Cookie 使用 HttpOnly, Secure, and SameSite=strict for 最大值 security. 客户端-边 getCookie 函数能 仅读取非-HttpOnly Cookie. 会话 ID 是不可见到 JavaScript, 所以 XSS cannot steal 它. 服务器 looks 上会话 on 每个请求.

动手试一试

  • JWT Decoder

    Decode JWT 到理解令牌-based 认证 as alternative 到 Cookie 会话.

  • Hash Generator

    会话 IDs 是经常 hashes — generate one 到 see 如何它们 look.

常见错误

错误写法

设置会话 Cookie 不使用 HttpOnly, exposing 它到 XSS theft.

正确做法

总是设置 HttpOnly on 会话 and 认证 Cookie. 这个 prevents JavaScript (包含 injected XSS scripts) 从读取 Cookie 通过 document.Cookie. Cookie 是 still 发送到 服务器 automatically.

错误写法

Omitting SameSite, leaving Cookie vulnerable 到 CSRF attacks.

正确做法

设置 SameSite 到 'Strict' or 'Lax' (modern 默认). 这个 prevents Cookie 从是 发送 on cross-site 请求, 哪个是 mechanism 的 CSRF attacks. Use Strict for 最大值 security, Lax 如果你 需要顶部-level cross-site 导航到 工作.

相关指南

练习 Cookie and 会话

2 个练习

练习 Cookie and 会话

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误