Cookie security attributes kiểm soát cookie exposure và transmission.
- HttpOnly: cookie không accessible qua document.cookie hay JavaScript — ngăn XSS đánh cắp session token; vẫn tự động gửi trong HTTP requests.
- Secure: cookie chỉ gửi qua HTTPS — ngăn network sniffing, bắt buộc trong production.
- SameSite: Strict (không gửi cookie trong bất kỳ cross-site request nào — kể cả click link từ email đến site của bạn; rất secure nhưng friction cao cho federated services); Lax (gửi trong top-level navigation GET nhưng không trong img/iframe/fetch cross-site — good balance, default Chrome từ 2020); None (gửi tất cả cross-site — phải kết hợp với Secure, dùng cho third-party cookies như OAuth flows, embedded widgets).
- Best practice cho session cookies: Set-Cookie: sessionId=abc; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600.
- Cookie prefixes tăng security: __Secure- prefix (phải có Secure flag, HTTPS only); __Host- prefix (phải có Secure, không có Domain, Path=/ — strongest, pinned to host).
- Max-Age vs Expires: Max-Age (seconds relative) ưu tiên hơn Expires (absolute datetime) vì không phụ thuộc client clock.
- Session vs Persistent cookies: session cookie (không có Max-Age/Expires) bị xóa khi browser close; persistent có expiry.
- Third-party cookies: đang bị phase out bởi browsers — Privacy Sandbox, Storage Access API là alternatives.
Cookie security attributes control cookie exposure and transmission.
- HttpOnly: the cookie is not accessible via document.cookie or JavaScript — prevents XSS from stealing session tokens; the cookie is still automatically sent in HTTP requests.
- Secure: the cookie is only sent over HTTPS — prevents network sniffing; mandatory in production.
- SameSite: Strict (cookie is not sent in any cross-site request — including clicking a link from email to your site; very secure but high friction for federated services); Lax (sent on top-level GET navigation but not in cross-site img/iframe/fetch — good balance; Chrome default since 2020); None (sent in all cross-site requests — must be combined with Secure; used for third-party cookies such as OAuth flows and embedded widgets).
- Best practice for session cookies: Set-Cookie: sessionId=abc; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600.
- Cookie prefixes increase security: __Secure- prefix (must have Secure flag, HTTPS only); __Host- prefix (must have Secure, no Domain, Path=/ — strongest, pinned to the host).
- Max-Age vs Expires: Max-Age (relative seconds) takes precedence over Expires (absolute datetime) because it does not depend on the client clock.
- Session vs Persistent cookies: a session cookie (no Max-Age/Expires) is deleted when the browser closes; a persistent cookie has an expiry.
- Third-party cookies: being phased out by browsers — Privacy Sandbox and the Storage Access API are the alternatives.