Node.js Course
Node.js
/
Advanced

CSRF Protection

Definition

Cross-Site Request Forgery. A vulnerability where a malicious site tricks a user's web browser into performing an unwanted action on a trusted site where the user is currently authenticated.

Explain Like I'm New

You log into `yourbank.com`. A cookie is saved in your browser. You leave the tab open and visit `evil.com`. Evil.com has a hidden form that submits a POST request to `yourbank.com/transfer?amount=1000&to=hacker`. Because your browser automatically attaches the bank cookie to the request, the bank thinks YOU made the request and transfers the money.

Real World Example

Financial applications or social media platforms where state-changing actions (deleting accounts, transferring funds) are done via cookie-based authentication.

Common Use Cases

  • •Protecting session-based applications

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Are JWTs stored in `localStorage` vulnerable to CSRF?

intermediate

  • How does a CSRF Token prevent this attack?

Flash Cards

Question

Are JWTs in localStorage vulnerable?

Click to reveal answer
Answer

No! CSRF exclusively relies on the browser's behavior of automatically sending Cookies. If you use JWTs in `localStorage` and manually attach them via `Authorization` headers, CSRF is completely impossible.

Question

How do tokens prevent it?

Click to reveal answer
Answer

The server generates a unique, random string (CSRF Token) and gives it to the frontend. When the frontend submits a form, it must include that token. When `evil.com` tries to forge a request, they don't know the secret token, so the server rejects the request.