ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Cyber Security Tutorial• 7 min read

Cross-Site Request Forgery (CSRF) & SameSite Cookies

Exploiting ambient credentials, Anti-CSRF tokens, and SameSite=Lax/Strict

CSRF tricks an authenticated victim into submitting an unauthorized state-changing request (like transferring money or changing passwords) to a vulnerable site where they are logged in.

How CSRF Exploits Ambient Credentials

When you visit an evil website, that site can contain an image or form that automatically triggers a POST request to your bank: <form action="https://bank.com/transfer" method="POST">.

By default, browsers attach ambient authentication cookies to cross-origin requests, so the bank treats the request as legitimate!

Mitigation 1: Anti-CSRF Tokens. Cryptographically random, unpredictable tokens generated on the server and verified on every POST/PUT/DELETE submission.

Mitigation 2: SameSite Cookie Attribute. Setting SameSite=Lax or SameSite=Strict instructs browsers never to send session cookies on cross-site requests.

Configuring Secure Session Cookies with SameSite
// Express / Node.js session cookie configuration
app.use(session({
  name: '__Secure-sessionId',
  secret: process.env.SESSION_SECRET,
  cookie: {
    httpOnly: true, // Prevents JavaScript from reading cookie (thwarts XSS)
    secure: true,   // Transmitted strictly over HTTPS
    sameSite: 'lax', // Blocks CSRF requests from third-party sites
    maxAge: 1000 * 60 * 60 * 2 // 2-hour expiration
  }
}));
Combines httpOnly, secure, and sameSite for robust defense against both XSS and CSRF.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which cookie attribute prevents the browser from sending session cookies along with cross-site third-party requests, mitigating CSRF attacks?