Use cookies 安全
Cookies 必须是 集合具有安全, HttpOnly, SameSite, 和 proper expiration. Learn Cookie attributes 和安全最佳实践.
- 1
Cookie 安全 attributes: 安全 (仅 sent 遍历 HTTPS), HttpOnly (不 accessible via JavaScript — prevents XSS theft), SameSite (Lax/Strict/None — controls cross-site sending, prevents CSRF), Domain (作用域), Path (作用域), Max-Age/Expires (lifetime), Partitioned (CHIPS — per-top-级别-site). 为会话 cookies: 安全 + HttpOnly + SameSite=Lax + 短 Max-Age.
- 2 Base64 编码器 →
编码 cookie values as base64 if they contain binary data or special characters. This ensures the cookie value is a valid cookie string (no spaces, semicolons, or commas). The server decodes base64 to recover the original value. For JSON cookies, encode the JSON string as base64.
- 3 HMAC 生成器 →
Sign cookies 具有 HMAC 到 prevent tampering. Cookie 值是: 数据 + "." + HMAC(secret, 数据). 开 receipt, 验证 HMAC 之前 trusting 数据. 此 allows stateless 会话 cookies — 会话数据是 在 Cookie (signed, 不 encrypted), 和服务器 verifies 签名无 数据库 lookup.
常见问题
- 当到 use HttpOnly?
- 总是, 为 cookies 该 browser needs 但 JavaScript 不 (会话 IDs, CSRF tokens). HttpOnly prevents XSS 从 stealing Cookie via document.Cookie. 仅异常是 cookies 该 JavaScript 必须读取 (e.g., 主题 preference) — 但这些应该不 是安全-sensitive.
- SameSite=Lax vs Strict vs None?
- Lax (默认): cookies sent 开顶部-级别 navigations (link clicks, form GET) 但不 开 cross-site POST 或 iframes — prevents CSRF 为最多 cases. Strict: cookies 仅 sent 为 same-site requests — strongest 但 breaks cross-site links (用户 follows link 到你的 site, 否 cookies sent, appears logged out). None: 总是 sent (requires 安全) — needed 为 third-party cookies (iframes, embeds).