Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 80 ยท Web Application Security

CSRF, SameSite and CORS

Learn how cross-site request forgery works, how tokens and SameSite cookies stop it, and how to avoid dangerous CORS misconfigurations, with Python simulations.

Browsers have a convenient habit: when your browser sends a request to a site, it attaches that site's cookies automatically, no matter which page triggered the request. That is how you stay logged in. It is also the root of cross-site request forgery (CSRF): a malicious page makes your browser send a request to a site where you are logged in, and the site sees your valid session cookie and believes you meant to do it.

A second, often confused topic is CORS (cross-origin resource sharing). CSRF is about causing actions; CORS is about reading responses. They are both controlled by browser rules about origins, so this lesson covers them together. You will learn the attack, three defenses (anti-forgery tokens, SameSite cookies and origin checks) and the CORS mistakes that turn a safe API into an open one. All "requests" here are Python simulations of what a browser and server would do. For how sessions and cookies work, see Sessions, Cookies and JWTs.

Origins and sites

An origin is the combination of scheme, host and port: https://shop.example:443 is one origin and https://api.shop.example is another. The same-origin policy stops a page from one origin reading data from another origin. A site is a looser idea (scheme plus the registrable domain, such as shop.example) used by cookies. https://app.shop.example and https://api.shop.example are different origins but the same site.

How CSRF works

Suppose a bank's site has a POST /transfer endpoint that identifies you only by your session cookie. A page on evil.example contains a hidden form that auto-submits to the bank. Your browser sends the form to the bank and includes your bank cookie, because that is what browsers do. The bank sees an authenticated request and moves the money. The attacker never saw the cookie and never needed to.

sequenceDiagram
    participant V as Victim browser
    participant E as evil.example
    participant B as bank.example
    V->>E: Opens a page
    E-->>V: Page with hidden form to bank.example
    V->>B: POST /transfer (cookie attached automatically)
    B->>B: Valid session, runs transfer
    B-->>V: 200 OK (attacker never sees it)

The forged request carries real credentials because the browser attaches them.

CSRF needs three ingredients: a state-changing action, cookie-based (automatic) authentication and request parameters the attacker can predict. Remove any one and the attack fails. A request that needs a custom header, or a secret value the attacker cannot guess, breaks the third ingredient.

Defense 1: anti-forgery tokens

The classic fix is the synchronizer token. The server puts a random, unguessable token in each form (and keeps a copy in the user's session). On submission it compares the two. The attacker's page cannot read the token because the same-origin policy blocks it from reading the bank's pages, so the forged request lacks it.

Python Tokens stop a forged request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Frameworks implement this for you (Django, Laravel and most others ship CSRF middleware that is on by default). Keep it enabled, send the token for every state-changing request, and never perform state changes on GET, because links and images trigger GET requests without any form.

Defense 2: SameSite cookies

The SameSite cookie attribute tells the browser when to attach a cookie to a request that originates from another site:

  • Strict: never sent on cross-site requests. Safest, but a user following a link from an email to your site arrives logged out on the first page.
  • Lax: sent on cross-site requests only for top-level navigations using safe methods (clicking a link), not for forms posted from another site or background requests. Most modern browsers treat a cookie without the attribute as Lax, but you should set it explicitly.
  • None: sent everywhere, but only together with Secure. Needed for genuine cross-site embeds.

A good session cookie looks like Set-Cookie: session=...; Secure; HttpOnly; SameSite=Lax; Path=/. The demo encodes the browser's rule so you can test combinations:

Python Does the browser send the cookie?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The forged form from the evil site is blocked by both Strict and Lax. That is why SameSite makes classic CSRF much harder. It is not complete protection, though: sibling subdomains count as the same site, older browsers ignore it, and some flows need None. Use it together with tokens.

Defense 3: checking Origin and fetch metadata

Browsers add an Origin header to cross-origin and POST requests, and modern ones send Sec-Fetch-Site (same-origin, same-site, cross-site, none). A server can reject state-changing requests whose Origin is not on its allow-list or whose Sec-Fetch-Site is cross-site. This check is cheap and good as an extra layer. Compare the origin exactly: https://bank.example.evil.example starts with https://bank.example but is not the same origin, so never use startswith.

CORS: reading, not acting

By default a page at https://evil.example cannot read the response from https://api.bank.example because of the same-origin policy. CORS is how a server opts in to sharing responses with other origins, using headers such as Access-Control-Allow-Origin. Two things to hold on to:

  1. CORS does not stop requests from being sent. It only controls whether the calling page's JavaScript may read the response. "Simple" requests (a basic POST form, a GET) are sent regardless, which is why CORS is not a CSRF defense.
  2. Non-simple requests (custom headers, JSON content type, PUT, DELETE) trigger a preflight OPTIONS request first, and the browser sends the real request only if the server approves.

Common misconfigurations:

  • Reflecting whatever Origin arrives into Access-Control-Allow-Origin while also sending Access-Control-Allow-Credentials: true. Every site on the internet can then read authenticated responses.
  • Trusting the null origin, which sandboxed iframes and local files can produce.
  • Substring or regex checks that accept bank.example.evil.example or evilbank.example.
  • A wildcard * on an API that returns data that is private by network position (an internal service, an intranet). Browsers refuse * together with credentials, but any website can still read such responses through a visitor's browser.
Python A safe and an unsafe CORS policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The safe policy answers yes only for the two genuine front ends. Notice the Vary: Origin header: when the response changes with the Origin header, caches must be told, or one origin's headers could be served to another.

Putting it together

A practical checklist for a cookie-based web app:

  • Keep your framework's CSRF protection on; send tokens with every state-changing request.
  • Set session cookies Secure; HttpOnly; SameSite=Lax (or Strict for sensitive apps).
  • Never change state with GET.
  • Validate Origin or Sec-Fetch-Site for unsafe methods as an additional check.
  • Treat CORS as an allow-list of exact origins; never reflect the request origin or combine * with private data.
  • Remember that XSS defeats all of this, since injected script runs same-origin and can read tokens. Fix XSS first.

APIs that authenticate with a bearer token in an Authorization header (which the browser does not attach automatically) are naturally not vulnerable to CSRF, but they have their own issues, covered in API Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does CSRF work?

    The attacker never sees the cookie. The victim's browser adds it to the forged request on its own.
  2. 2. How does an anti-forgery token stop a forged form?

    The same-origin policy prevents the attacker's page from reading the real page that contains the token.
  3. 3. Which SameSite setting blocks a hidden cross-site form POST while still sending the cookie when the user clicks a link to your site?

    Lax sends cookies on cross-site top-level GET navigations but not on cross-site POSTs or background requests.
  4. 4. What does CORS control?

    CORS governs reading responses. Simple requests are sent regardless, so CORS is not a CSRF defense.
  5. 5. Which CORS configuration is dangerous?

    Reflecting any origin with credentials lets every website read authenticated responses on behalf of your logged-in users.

Summary

  • CSRF abuses automatically attached cookies to make a logged-in browser perform an action the user did not choose.
  • Defend with anti-forgery tokens, SameSite cookies (Lax or Strict), Secure and HttpOnly, and origin or fetch-metadata checks.
  • Never change state with GET; keep framework CSRF protection enabled.
  • CORS decides whether pages from other origins may read responses; it does not prevent requests being sent.
  • Use exact-match origin allow-lists, avoid reflecting Origin, avoid trusting null, and add Vary: Origin.
  • XSS breaks every CSRF defense, so fix it first.

Next: Input Validation and Sanitization, the habit of deciding exactly what you accept before any of it reaches your code.