Secure and SameSite Cookie Flags
What you'll learn: How to use the Secure and SameSite cookie flags to prevent token interception and CSRF attacks.
The Problem with Unsecured Cookies
In the previous lesson, you learned that HttpOnly cookies prevent JavaScript from reading tokens. But that's only half the security story. Without additional flags, cookies can still be sent over unencrypted connections or submitted to malicious sites by your browser automatically.
The Secure Flag
The Secure flag ensures your cookie is only transmitted over HTTPS connections, never plain HTTP. Think of it like sending sensitive mail in an armored truck instead of leaving it on a park bench.
When you set a cookie with the Secure flag, browsers refuse to send it over unencrypted connections. This prevents man-in-the-middle attackers from intercepting your tokens on insecure networks.
Set-Cookie: token=abc123; HttpOnly; Secure
The SameSite Flag
The SameSite flag prevents Cross-Site Request Forgery (CSRF) attacks by controlling when browsers send cookies with cross-origin requests.
Three values exist:
Strict: Cookie only sent to the same site that set it. Maximum protection, but breaks some legitimate cross-site flows.Lax: Cookie sent with top-level navigation (clicking links) but not with cross-site POST requests. Good balance.None: Cookie sent everywhere, but requires theSecureflag.
Set-Cookie: token=abc123; HttpOnly; Secure; SameSite=Strict
When to Use Which
For authentication tokens, use Secure always (in production with HTTPS) and SameSite=Lax or Strict depending on whether you need cross-site link navigation to work seamlessly.
Key Takeaway: Always set Secure to enforce HTTPS-only transmission and SameSite (typically Lax or Strict) to prevent CSRF attacks—these flags are essential layers of cookie-based authentication security.