Security
Secure Cookie Flags (HttpOnly, Secure, SameSite)
Master secure cookie configurations in JavaScript. Learn to prevent session hijacking using HttpOnly, Secure, and SameSite cookie flags.
1. Introduction
Cookies are key-value pairs stored in the browser that are sent with HTTP requests automatically. They are commonly used to manage user sessions. To prevent session hijacking and cross-site scripting (XSS) attacks, servers configure cookies using specific security flags: HttpOnly, Secure, and SameSite.
2. Why It Matters
Authentication cookies are target resources for attackers. If a cookie lacks security flags:
• Attackers can steal session keys using simple client-side scripts via document.cookie (XSS).
• Sniffers can intercept cookies sent over unencrypted HTTP channels.
• Malicious sites can perform state-changing actions by exploiting the browser's automatic cookie transmission (CSRF).
3. Real-World Analogy
Think of a Vip Lounge Verification Ticket:
- Normal Ticket (No security flags): A paper voucher in your hand. Anyone can look at it (access via script), photocopy it (XSS steal), or hand it to someone else to enter the lounge for them.
- HttpOnly Flag (Locked display box): The teller locks the ticket inside a heavy glass display box. You can see the ticket (the browser sends it with requests), but you cannot touch it, copy it, or hand it to others directly.
- Secure Flag (Armored courier): The ticket is only transported via armored trucks (HTTPS encryption). If a courier tries to transport it in an open delivery vehicle (unencrypted HTTP), they are turned away.
- SameSite Flag (Entry checkpoint): The club security guards check the origin of the guest: if you walk in from a side door connected to a competing casino (cross-origin site), they refuse to accept your ticket.
4. Secure Cookie Flags
When setting the Set-Cookie response header, servers append these flags to secure the cookie:
1. HttpOnly:
Blocks client-side scripts (like JavaScript's document.cookie) from reading the cookie. This protects the cookie from theft via XSS vulnerabilities.
2. Secure:
Instructs the browser to only transmit the cookie over encrypted HTTPS connections. This prevents the cookie from being intercepted by attackers on the network.
3. SameSite:
Controls whether cookies are sent during cross-origin requests, blocking CSRF attacks:
• SameSite=Strict: The cookie is only sent for same-site requests.
• SameSite=Lax: The cookie is sent during cross-origin navigations using safe HTTP methods (like clicking a GET link to your site), but is blocked for state-changing requests (like POST forms or image embeds).
• SameSite=None: The cookie is sent with all cross-site requests. This requires the Secure flag to be set as well.
5. Practical Example
This Express backend configuration sets a secure session cookie with all security flags enabled:
6. Common Mistakes
- Not enabling Secure flags in production: If the
Secureflag is omitted in production, browsers will transmit session cookies over unencrypted HTTP connections, allowing attackers on public Wi-Fi networks to intercept session tokens using packet sniffers.
7. Quick Quiz
Q1: Which cookie security flag prevents JavaScript's document.cookie API from reading session tokens?
A) Secure
B) HttpOnly
Answer: B — The HttpOnly flag blocks client-side script access to the cookie, protecting it from theft via XSS.
8. Scenario-Based Challenge
The CSRF-Vulnerable Session Store:
An API server configures session cookies: res.cookie("session", id). Security audits report vulnerabilities to CSRF attacks. Modify the cookie options parameters to implement protection using SameSite Lax controls.
9. Debugging Exercise
Explain why this local development login API throws an error or fails to authenticate, and how to resolve it:
// Express Login Route (Local Dev Environment: http://localhost:3000)
app.post('/api/login', (req, res) => {
res.cookie('token', 'session-data', {
httpOnly: true,
// Bug: local development runs on unencrypted HTTP!
secure: true, // browser rejects cookie because connection is not HTTPS!
sameSite: 'strict'
});
res.send('Success');
});
View Solution
Diagnosis: The cookie configures the secure: true flag. Because local development servers typically run on unencrypted http://localhost, the browser blocks the cookie, preventing authentication.
Fix: Disable the secure flag dynamically in local development environments (except for localhost, which some modern browsers exempt):
app.post('/api/login', (req, res) => { const isProd = process.env.NODE_ENV === 'production';
res.cookie('token', 'session-data', { httpOnly: true, secure: isProd, // Enable 'secure' only in production HTTPS environments! sameSite: 'lax' }); res.send('Success'); });
10. Interview Questions
🟢 Q1: Describe the security benefits of using HttpOnly, Secure, and SameSite flags on session cookies.
Answer:
• HttpOnly: Prevents client-side scripts from reading the cookie via document.cookie, protecting session tokens from theft via XSS.
• Secure: Ensures the cookie is only sent over encrypted HTTPS connections, protecting it from interception via network packet sniffers.
• SameSite: Controls whether cookies are sent during cross-origin requests, blocking CSRF attacks by preventing browsers from automatically attaching cookies to requests originating from external sites.
11. Production Considerations
- • Expire Session: Set short expiration lifetimes (using the
maxAgeorexpiresparameters) on session cookies, and clear expired sessions on the server side to minimize the impact of session hijacking.