EasyFrontend Security📖 Theory Question

What is CSRF and how do SameSite cookies and CSRF tokens prevent it?

💡

Hint

Forged cross-origin request that rides on the victim's cookies — SameSite blocks cookie sending; CSRF token requires secret the attacker doesn't have

Full Answer

CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into making an unintended request to a site where they're authenticated. The browser automatically sends cookies, so the server sees it as legitimate.

<!-- On attacker's site -->
<img src="https://bank.com/transfer?to=attacker&amount=1000" />
<!-- Browser auto-sends bank.com cookies with this request -->

Prevention 1: SameSite cookies

  • SameSite=Strict — cookie never sent on cross-origin requests. Breaks OAuth flows.
  • SameSite=Lax — cookie sent on top-level navigations (GET links) but not on embedded requests (img, form POST from other sites). Good default.
  • SameSite=None; Secure — sent everywhere (cross-origin). Requires HTTPS.

Prevention 2: CSRF tokens

// Server sets a CSRF token in a readable cookie (not HttpOnly) or in page HTML
// Client reads it and sends it as a header
const csrfToken = getCookieValue('csrf-token');
fetch('/api/transfer', {
  method: 'POST',
  headers: { 'X-CSRF-Token': csrfToken }, // attacker can't read this
});

Attackers can't read the CSRF token from a different origin (same-origin policy), so they can't forge the header.

More Frontend Security Questions

EasyWhat is XSS (Cross-Site Scripting) and how do you prevent it?EasyWhat is a Content Security Policy (CSP) and how does it work?EasyWhat is clickjacking and how do you prevent it?EasyWhat security HTTP response headers should every production frontend set?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint