Network Security Basic

What is a CSRF Attack? How do you prevent it?

AI Practice

What is CSRF?

CSRF (Cross-Site Request Forgery) tricks an authenticated user into unknowingly sending a malicious request to a trusted website — the browser automatically attaches the user's session cookie, so the server thinks it's a legitimate request.

How It Works

1. User logs into bank.com — browser stores a session cookie
2. User is lured to evil.com
3. evil.com automatically sends: bank.com/transfer?to=attacker&amount=10000
4. Browser automatically attaches the bank.com cookie
5. Server thinks it's the user — transfer goes through
<!-- Malicious auto-submitting form on evil.com -->
<form action="https://bank.com/transfer" method="POST">
  <input type="hidden" name="to" value="attacker" />
  <input type="hidden" name="amount" value="10000" />
</form>
<script>document.forms[0].submit()</script>

CSRF vs XSS

XSS CSRF
Method Inject malicious scripts Forge legitimate requests
Exploits Site trusting user input Browser auto-sending cookies
Goal Steal information Execute unauthorized actions

Prevention

1. CSRF Token (most common)

The server generates a random token per session, embeds it in forms, and validates it on every request:

<form method="POST" action="/transfer">
  <input type="hidden" name="csrf_token" value="a1b2c3d4e5..." />
  <!-- other fields -->
</form>

Restrict cookies from being sent on cross-site requests:

Set-Cookie: session=abc; SameSite=Strict; Secure; HttpOnly
Value Behavior
Strict Never send cookie cross-site
Lax (default) Allow GET cross-site, block POST
None Allow cross-site (requires Secure)

3. Validate Referer / Origin Header

Check that the request origin is a trusted domain:

// Backend validation
if (req.headers.origin !== 'https://bank.com') {
  return res.status(403).json({ error: 'Forbidden' })
}

4. Add Second-Factor Verification for Sensitive Actions

For transfers, password changes, etc., require CAPTCHA or password re-entry.

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring

Copyright © 2026 Wood All Rights Reserved · FE Interview Hub