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
- The server sends a
设置-Cookieheader in the HTTP response:设置-Cookie: 会话=abc123; HttpOnly; Secure; SameSite=Strict. - The browser stores the cookie.
- On every future request to that domain, the browser includes it:
Cookie: 会话=abc123. - 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 (viadocument.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.最大值-AgeorExpires— how long the cookie lives. Without this, the cookie is a "会话 Cookie" that clears when the browser closes.