Course contentsShow
← Software Engineering
Lesson 1010 of 1,93331. Authentication and AuthorizationFree lesson

Cookie Security: HttpOnly, Secure, and SameSite

Essential cookie flags that prevent XSS, man-in-the-middle attacks, and CSRF vulnerabilities.

Cookie Security: HttpOnly, Secure, and SameSite

What you'll learn: How three critical cookie flags protect your session cookies from common web attacks.

When you store session IDs in cookies (as you learned in session-based authentication), those cookies become valuable targets for attackers. Three simple flags transform your cookies from vulnerable data stores into hardened security tokens.

HttpOnly: Blocking JavaScript Access

The HttpOnly flag prevents JavaScript from reading your cookie through document.cookie. This is your primary defense against Cross-Site Scripting (XSS) attacks. Even if an attacker injects malicious JavaScript into your page, they cannot steal session cookies marked HttpOnly.

Analogy: It's like a safety deposit box that only bank employees can open—customers (JavaScript) can't access it directly.

Set-Cookie: sessionId=abc123; HttpOnly

Secure: Encryption Required

The Secure flag ensures cookies are only transmitted over HTTPS connections, never plain HTTP. This protects against man-in-the-middle attacks where attackers eavesdrop on unencrypted network traffic.

Set-Cookie: sessionId=abc123; HttpOnly; Secure

SameSite: Preventing Cross-Site Requests

The SameSite attribute defends against Cross-Site Request Forgery (CSRF) attacks by controlling when browsers send cookies with cross-origin requests. Three values exist:

  • Strict: Cookie never sent on cross-site requests (maximum security)
  • Lax: Cookie sent only with top-level navigation (GET requests, links)
  • None: Cookie sent everywhere (requires Secure flag)
Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict

Defense in Depth

Use all three together for robust session cookie protection. They work as layers—if one defense fails, others remain.

Key Takeaway: Always set HttpOnly, Secure, and SameSite flags on authentication cookies to prevent XSS, interception, and CSRF attacks—these flags are free security with no performance cost.