🛡️ Cookie Security Best Practices
Essential security measures for protecting cookies from common web exploits and vulnerabilities.
🔐 Secure Cookie Flags
HttpOnly
Prevents client-side scripts from accessing cookies to mitigate cross-site scripting (XSS) attacks.
document.cookie = "session_id=abc123; HttpOnly; Secure; Path=/";
Recommended for session cookies and sensitive data.
Secure
Ensures cookies are only sent over HTTPS connections.
document.cookie = "token=xyz456; Secure; SameSite=Strict";
Mandatory for production environments and sensitive applications.
SameSite
Controls cross-site cookie sharing to prevent CSRF and session fixation attacks.
document.cookie = "auth_token=789abc; SameSite=Strict";
Use Strict for sensitive cookies, Lax for most public access, and None with Secure for cross-site dependencies.
💀 Cookie Vulnerability Patterns
XSS Exploits
Attackers can steal cookies by injecting malicious JavaScript if the
HttpOnly
flag is missing.
Always use HttpOnly for session and authentication tokens.
CSrf (Cross-Site Request Forgery)
Unauthenticated requests can exploit session cookies if the
SameSite
flag isn't used.
Always configure SameSite=Strict for session cookies.
Man-in-the-Middle (MITM)
Cookies without the
Secure
flag can be intercepted over unencrypted channels.
Always require HTTPS by using Secure flag.
🛡️ Secure Cookie Configuration
1. Minimal Permissions
Limit cookie scope with Path and Domain attributes.
path=/app; domain=.example.com;
2. Short Lifespan
Use Max-Age instead of session cookies for predictable cleanup.
expires=Thu, 01 Jan 2024 00:00:00 GMT;
3. Secure by Default
Always enforce Secure and HttpOnly for production cookies.
HttpOnly; Secure;