In this lesson, you will learn how to harden your authentication cookies against XSS and CSRF attacks by leveraging browser-level security attributes.
When you store a session identifier in a cookie, you are essentially handing the user a "key" to their account. If an attacker can steal that key or force the browser to use it maliciously, your application’s authentication is compromised. We use two primary flags to lock these keys down: HttpOnly and SameSite.
Preventing XSS with HttpOnly
Cross-Site Scripting (XSS) occurs when an attacker injects malicious JavaScript into your page. By default, JavaScript can read your cookies via document.cookie. If a session token is accessible here, the injected script can simply exfiltrate it.
By setting the HttpOnly flag, you instruct the browser that the cookie cannot be accessed through the DOM. Even if an attacker succeeds in running scripts on your site, they won't be able to grab the session token.
Preventing CSRF with SameSite
Cross-Site Request Forgery (CSRF) is an attack where a user is tricked into performing actions on your site from a different, malicious site. The SameSite attribute controls whether your cookie is sent with cross-site requests.
SameSite=Strict: The cookie is only sent if the request originates from the same site where the cookie was set.SameSite=Lax(Recommended): The cookie is withheld on cross-site subrequests (like images or frames) but is sent when a user clicks a link from an external site to yours.
Implementation
In a Node.js environment, typically using a framework like Express, you configure these when setting the header:
res.cookie('session_id', 'your-secret-token', {
httpOnly: true, // Prevents JS access (XSS defense)
secure: true, // Ensures cookie is sent over HTTPS only
sameSite: 'lax', // Prevents cross-site forgery (CSRF defense)
maxAge: 3600000 // 1 hour expiry
});
By combining these, you create a "defense-in-depth" posture. HttpOnly renders the cookie invisible to attackers' scripts, and SameSite limits the contexts in which the browser will automatically include the cookie, significantly reducing the surface area for session hijacking.
Key Takeaway: Use HttpOnly to block script-based cookie theft and SameSite=Lax to restrict cookies from being abused in cross-site requests.