API Fundamentals Course
API Fundamentals
/
Advanced

CSRF

Definition

Cross-Site Request Forgery. A malicious exploit where unauthorized commands are transmitted from a user that the web application trusts, typically by exploiting the browser's automatic inclusion of session cookies.

Explain Like I'm New

You log into your Bank. The bank gives you a cookie. You open a new tab and visit `Evilsite.com`. EvilSite contains a hidden form that secretly submits a request to `Bank.com/transfer`. Because you are still logged in, your browser automatically attaches the cookie, and the bank processes the fake transfer.

Real World Example

An attacker posting an invisible 1-pixel image on a forum. The image URL is actually `src="http://bank.com/transfer?amount=1000&to=hacker"`. When users load the forum, their browser tries to 'fetch' the image, accidentally transferring money.

Common Use Cases

  • •Security
  • •Cookie management

Terminal Output

bash / terminal
/* The Traditional CSRF Token Defense Pattern (for monolithic apps): */ // 1. The server generates a random string (CSRF Token) and puts it in a hidden // field on the login form. <form action="/transfer" method="POST"> <input type="hidden" name="_csrf" value="8f3jd92k3jd"> <button>Transfer Money</button> </form> // 2. When submitted, the server verifies the cookie AND verifies the token matches. // Evilsite can force your browser to send the cookie, but Evilsite cannot read // the random token from your HTML, so their forged request will fail.

Interview Questions

basic

  • What browser setting on a Cookie is the modern, built-in defense against CSRF attacks?

intermediate

  • Why are APIs that strictly use JWTs in the `Authorization` header immune to CSRF?

Flash Cards

Question

Cookie setting?

Click to reveal answer
Answer

The `SameSite` attribute (e.g., `SameSite=Lax` or `Strict`). It tells the browser to never attach the cookie if the request originated from a different domain.

Question

Why are JWTs immune?

Click to reveal answer
Answer

Because CSRF completely relies on the browser AUTOMATICALLY attaching the authentication cookie. If you use a JWT in the `Authorization` header, the frontend JavaScript must manually attach it. EvilSite's JavaScript cannot read your JWT, so it cannot forge the request.