SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

CSRF

A trick that makes your browser send a request you never meant to send, and how to stop it.

⏱ 12 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

CSRF (Cross-Site Request Forgery) is a trick that makes a logged-in user’s browser send a request they never meant to send, to a site that trusts them.

  • Browsers attach cookies automatically to every request to a site, even if the request was started by a different site.
  • So an evil page can submit a hidden form to your bank, and the browser adds your login cookie. The bank cannot tell it from a real click.
  • The fix is to make the server require something an attacker cannot copy: SameSite cookies, CSRF tokens, an Origin check, or a custom header.

02Concept: What is it?

Think about how a cookie works. Once you log in to bank.example, the browser stores a session cookie. After that, every request to bank.example carries that cookie. The browser does this on its own. It does not ask where the request came from.

That is the weakness. If you visit evil.example while still logged in to the bank, the evil page can quietly send a request to the bank (a form that submits itself, or an image or link). The browser attaches your bank cookie, and the bank thinks you asked for it.

How a CSRF attack works
🧑‍💻Youlogged in to the bank
→↓open a link
😈evil.examplehidden form
→↓POST /transfer + your cookie
🏦bank.examplethinks it was you
The attacker never sees the cookie. They only make the browser send it.

What CSRF is not

AttackWhat happensThe key difference
CSRFThe attacker makes your browser send a requestThe attacker cannot read the answer. It abuses the browser’s automatic cookies.
XSSThe attacker runs script inside the trusted pageThe attacker can read pages and tokens. XSS can also beat CSRF defences.
CORS misconfigurationA site is allowed to read another site’s responsesCORS is a read-permission rule. It does not, on its own, stop a forged write.
🧠State-changing requests are the target
CSRF is about changing things (transfer money, change email, delete data), because the attacker cannot see the response. Never let a GET request change data.

03Real-Life Example

🍵The Signed Blank Cheque
You have an account at a bank. The bank accepts any cheque that has your signature stamp on it, and your assistant stamps everything you hand over without looking. A stranger gives you a friendly letter. Inside is a cheque made out to the stranger, and you pass it along with your other post. The assistant adds your stamp, and the bank pays. The bank did see a valid stamp. It did not see that the cheque was your idea.
Cheque story
CSRF
The signature stamp
The session cookie
The assistant who stamps automatically
The browser that attaches cookies automatically
The stranger’s letter
The attacker’s web page
The cheque made out to the stranger
The forged request (transfer to the attacker)
The bank only checking the stamp
A server that only checks the cookie
A secret code the stranger cannot know
A CSRF token
Checking the cheque came from your own desk
Checking the Origin header
The fix: ask for something the attacker cannot copy
🏦Bank pageincludes a secret form token
→↓you submit token + cookie
✅Bank checks bothcookie AND token
😈Evil pagecannot read the token
→↓cookie only
⛔Rejectedtoken missing

04Why Do We Need It?

💸Stops forged actions
Stops money transfers, password changes, and deletes that the user never asked for.
🍪Cookies are everywhere
Any site that uses cookie sessions is exposed unless it adds a defence.
🔒Login is not enough
Being logged in proves who you are, not that you meant this request.
🧑‍💼Admin pages are a prize
A forged request in an admin’s browser can do a lot more than one in a normal user’s.
🧱Cheap to defend
A few lines of config or a standard library close most of the gap.
📋A security checklist item
It appears in the standard web security lists and in many audits.
If the browser adds your login by itself, the server must also check that the request really came from its own pages.

05Where Do We Use It?

🏦Web apps with cookie sessions
Banks, shops, admin panels, dashboards: anywhere a cookie proves who you are.
📝HTML forms
Every form that changes data should carry a CSRF token (frameworks do this for you).
🔌Cookie-based APIs
A JSON API called from your own front end with a cookie is as exposed as a form.
🖥️Routers and local devices
Admin pages on a home network can be hit by a forged request from a web page.
🧩Login and OAuth flows
The state parameter is a CSRF defence for the login callback.
🚫Not classic CSRF
APIs that need an Authorization header added by your own JavaScript are not hit by classic CSRF.

06Types / Parts / How It Works

The main defences

DefenceHow it worksGood and bad
SameSite cookiesThe cookie is not sent on cross-site requests (Strict) or only on top-level GET navigations (Lax)Easy and strong. Lax is the default in many modern browsers. Does not separate sibling subdomains, and old browsers differ.
Synchronizer tokenThe server puts a random token in each form and in the session, and checks they matchClassic and strong. Needs server-side state per session.
Double-submit cookieA random value is sent both in a cookie and in a header or form field. They must matchNeeds no server state. Weaker if an attacker can set cookies on your domain. Signed values help.
Origin / Referer checkReject a state-changing request whose Origin is not your own siteCheap extra layer. Some requests have no Origin, so do not rely on it alone.
Custom headerRequire a header such as X-Requested-With on API callsA cross-site form cannot add it, and a cross-site script call triggers a CORS preflight.
Re-authenticationAsk for the password or a code for risky actionsStrong for sensitive steps. Costs user effort.
Layers of defence
Browser side
🍪SameSite cookie
🧩CORS preflightfor custom headers
Server side
🎟️CSRF token
🏷️Origin check
🔐Re-auth for big actions
Browser helps Server checks
Use more than one. The browser stops most attacks, and the server stops the rest.

SameSite values

Set-Cookie examples
Set-Cookie: session=abc; Secure; HttpOnly; SameSite=Lax
Set-Cookie: session=abc; Secure; HttpOnly; SameSite=Strict
Set-Cookie: session=abc; Secure; HttpOnly; SameSite=None   (only with Secure; sent on cross-site requests)
VisualizerWill the forged request work?Start with a session cookie, SameSite=None and no checks: the attack works. Then turn on SameSite=Lax or Strict, a CSRF token or an Origin check, and try GET and POST. Finally switch to an Authorization header.
How does the browser prove who you are?
Forged request method
Cookie SameSite
😈evil.exampleauto-submits a hidden form
→↓tricks
🧑‍💻Victim’s browserlogged in to the bank
→↓POST /transfer?to=attacker
🏦bank.examplesees the login cookie
💸Attack works
Login attached?
yes
SameSite=none
CSRF token
not used
attacker cannot read it
Origin seen
https://evil.example
not checked
Result
money moved
state change
The cookie was attached and nothing on the server could tell this request from a real click. The money moves. This is CSRF.

A simplified model of the classic attack: the forged request comes from a form or link on another site. Browsers differ in details, and a site on the same registrable domain counts as “same-site”, so SameSite does not separate sibling subdomains. Use several defences together.

07How to Use It / Steps / Implementation

Protecting a cookie-based app

  1. 1
    Use your framework’s CSRF protection
    Most web frameworks have it built in. Turn it on, and do not disable it to “make a form work”.
  2. 2
    Set SameSite on the session cookie
    Use Lax at least, and Strict when the app does not need links from other sites to arrive logged in. Add Secure and HttpOnly too.
  3. 3
    Add a CSRF token to every state-changing request
    Put a random, per-session (or per-request) token in forms and in the headers of your JavaScript calls. Reject requests without a valid one.
  4. 4
    Check Origin (and Referer if Origin is missing)
    For POST, PUT, PATCH and DELETE, compare the Origin to your own site. Treat it as an extra layer.
  5. 5
    Never change data on GET
    GET must be safe. Use POST, PUT, PATCH or DELETE for changes. Link prefetching and image tags use GET.
  6. 6
    Protect risky actions again
    Changing an email, password or payout account? Ask for the current password or a one-time code.
  7. 7
    Fix XSS too
    A cross-site scripting hole lets an attacker read your CSRF token and make real requests from your page. CSRF defences do not survive XSS.
💡Do APIs with tokens in headers need CSRF protection?
If your API reads the login only from an Authorization header that your JavaScript adds, the browser never sends it by itself. A forged form cannot add it, so classic CSRF does not apply. But if the same API also accepts a cookie, it is exposed again.
⚠️CORS is not a CSRF defence
CORS controls which sites may read your responses. A simple cross-site form POST is sent without a preflight, and the damage is done on the server whether or not the browser lets the page read the answer.

08Key Terms to Know

TermMeaning in easy words
CSRFCross-Site Request Forgery: tricking a browser into sending a request the user did not intend
Session cookieA cookie that proves a user is logged in. The browser attaches it automatically
SameSiteA cookie setting that limits sending the cookie on cross-site requests (Strict, Lax, None)
CSRF tokenA random secret that must come back with each state-changing request
Synchronizer tokenA token stored on the server per session and compared on each request
Double-submit cookieThe same random value is sent in a cookie and in a header or field. They must match
Origin headerA header that tells the server which site started the request
Same-origin policyBrowser rule that stops a page from reading data from another origin
PreflightAn OPTIONS request the browser sends first for some cross-site requests
Safe methodA method that must not change data (GET, HEAD, OPTIONS)
Login CSRFForcing a user to log in as the attacker’s account. The OAuth state parameter helps stop it

09Pros, Cons and Trade-offs

✅ Pros
  • SameSite stops most attacks with one setting
  • Standard tokens are well understood and supported by frameworks
  • Layers of defence add up
  • Header-based auth avoids the problem entirely
  • Cheap compared with the damage it prevents
⚠️ Cons
  • Tokens add code in forms and in JavaScript calls
  • Synchronizer tokens need server-side state
  • SameSite rules differ by browser and change over time
  • Origin is not always sent
  • A cross-site scripting bug breaks all of it

Trade-offs

ChoiceWe gainWe lose
SameSite=StrictStrongest cookie protectionUsers arriving from a link may look logged out until they click again
SameSite=LaxGood protection with normal links workingGET requests are still sent cross-site, so GET must stay safe
Synchronizer tokenStrong, simple to reason aboutPer-session server state, and care with caching and multiple tabs
Double-submit cookieNo server stateWeaker against attackers who can write cookies (use signed values)
Authorization headerImmune to classic CSRFThe app must store the token in JavaScript, which raises XSS exposure

10Common Problems and Mistakes

Common mistakes

  1. Changing data with GET. A link or an image tag then triggers the change.
  2. Trusting only the cookie. The cookie proves who you are, not that the request was intended.
  3. Thinking JSON means safe. A cross-site form can sometimes send content that your server happily parses as JSON if it ignores the Content-Type.
  4. Relying on CORS. CORS does not stop the request from being sent.
  5. Reusing one token forever, or sharing it across users. Make tokens random, tied to the session and unpredictable.
  6. Putting the token in the URL. It can leak through logs and the Referer header.
  7. Disabling CSRF checks for convenience on an endpoint, then forgetting about it.

Things to watch

🌐Subdomains
Sibling subdomains count as the same site, so SameSite does not separate them. An XSS on one can attack another.
🧾Missing Origin
Some requests (and older browsers) send no Origin. Decide what your server does in that case.
🕳️Third-party embeds
If your app must work inside another site’s page, you need SameSite=None; Secure, and stronger tokens.
🧪Test it
Write a test that sends a state-changing request without a token and expects a refusal.

11Real-World Examples

🧰Web frameworks
Many frameworks (Django, Rails, Spring Security, ASP.NET and others) ship CSRF tokens for forms by default.
🍪Browser defaults
Modern browsers treat cookies without a SameSite setting as Lax in many cases, which removed a lot of the risk.
🏦Banks
Sensitive actions often ask for a one-time code in addition to being logged in.
🛒Shops
Checkout and address changes use per-session tokens so a forged form cannot change them.
🔁Single-page apps
SPAs often send the token in a header, read from a cookie or a meta tag.
🔑OAuth logins
The state parameter ties the login callback to the browser that started it.
📝Note
Browser behaviour for SameSite and third-party cookies keeps changing. Check the current rules for the browsers you support.
Mini case: a forged email change
😈Hidden formPOST /account/email
→↓cookie attached?
🍪SameSite=Laxblocks cross-site POST
→↓no cookie
⛔Refused401 / 403

12Related Topics to Read Next

Cookies and CORS→

Cookies are what CSRF abuses, and CORS is often mistaken for a defence.

Session vs Token Based Auth→

Cookie sessions are exposed, header tokens are not (to classic CSRF).

Input Validation→

Another core web defence, aimed at attacks inside the input.

OpenID Connect (OIDC)→

State and nonce protect the login flow from forged requests.

HTTP / HTTPS→

Methods, headers and cookies are all part of HTTP.

Authentication vs Authorization→

Being authenticated does not mean the request was intended.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a forged request sent by the victim’s browser with their cookies.
  • ✔Why it works: browsers attach cookies automatically to every request to that site.
  • ✔Targets: actions that change things. The attacker cannot read the answer.
  • ✔Defences: SameSite cookies, CSRF tokens, Origin check, custom header, re-auth.
  • ✔Rule: GET must never change data.
  • ✔Not enough alone: CORS, or hiding the form. Use layers.
  • ✔Header auth: Authorization-header APIs avoid classic CSRF, until a cookie is also accepted.
  • ✔One line: “The cookie says who you are. The token says you meant it.”
← Previous
OpenID Connect (OIDC)
Next →
Input Validation