Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Broken Access Control

CSRF and Cross-Origin Access Control

Learn how cross-site request forgery abuses logged-in browsers, how CSRF tokens, SameSite cookies and Origin checks stop it, and how to configure CORS without opening your API.

Some access control failures are about who sends the request from the browser. Browsers automatically attach cookies to requests, even requests triggered by another website. That convenience is the root of cross-site request forgery (CSRF), and the related rules about which sites may read your responses (the same-origin policy and CORS) are easy to misconfigure.

The CSRF idea

You are logged in to bank.example, so your browser holds a session cookie. You then visit a malicious page. That page contains a hidden form that submits to bank.example/transfer. Your browser dutifully attaches the cookie, and the server sees a valid, authenticated request. It cannot tell that you never intended it.

sequenceDiagram
  participant V as Victim browser
  participant E as Other site (hostile)
  participant B as bank.example
  V->>B: Log in (cookie stored)
  V->>E: Visit page
  E-->>V: Page with hidden auto-submitting form
  V->>B: POST /transfer + victim's cookie
  B-->>V: Transfer done (server thinks it was intended)

The attacker never sees the cookie or the response. They only cause an action.

CSRF affects state-changing requests (transfers, email changes, deletes) that rely only on cookies for authentication. It does not matter how strong the password is; the request is legitimate in every technical sense.

Defenses

  1. SameSite cookies. SameSite=Lax (default in modern browsers) withholds the cookie on cross-site POSTs and most subrequests; Strict withholds it on nearly all cross-site navigation. This blocks most classic CSRF.
  2. Anti-CSRF tokens. The server embeds an unpredictable token in each form, tied to the session, and rejects submissions without the right value. A hostile site cannot read your page (same-origin policy), so it cannot know the token.
  3. Check Origin and Referer. For state-changing requests, accept only your own origin.
  4. Use proper HTTP methods. Never change state on GET: links and image tags would trigger it.
  5. Custom headers for APIs. Requiring a header such as X-Requested-With forces a CORS preflight that hostile sites fail.
  6. Re-authentication for the most sensitive actions.
Python A CSRF token in action

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 include this: Laravel's @csrf, Django's {% csrf_token %}, Spring Security's CSRF filter. Make sure it is on and that your JavaScript sends the token with fetch calls too.

The same-origin policy and CORS

An origin is scheme + host + port: https://shop.example:443. By default a script on one origin cannot read responses from another origin. This is the same-origin policy, and it protects your data from hostile pages.

CORS (Cross-Origin Resource Sharing) is how a server relaxes that rule on purpose. The server sends headers such as:

TEXT
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Credentials: true

CORS is not an authentication or CSRF defense. It controls which origins can read responses in a browser. A command-line client ignores CORS entirely.

Common CORS mistakes (all access-control failures):

Mistake Why it is dangerous
Access-Control-Allow-Origin: * on endpoints with private data Any site's scripts can read the responses (only safe for truly public data without credentials)
Reflecting the request's Origin header back with credentials allowed Equivalent to allowing every site to act as the user
Allowing the null origin Sandboxed iframes and local files can send Origin: null
Loose regex such as endsWith("example.com") evilexample.com matches
Trusting all subdomains One compromised or abandoned subdomain breaks everything
Python A strict CORS allow-list

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 Vary: Origin header tells caches that the response depends on the requester's origin.

Clickjacking: a cousin worth knowing

In clickjacking, a hostile page loads your site in an invisible iframe and tricks the user into clicking its buttons. Defend with Content-Security-Policy: frame-ancestors 'none' (or 'self'), plus the older X-Frame-Options: DENY. The next chapters cover more headers in the misconfiguration lessons.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does CSRF work?

    The server sees a valid session cookie and cannot tell the request was initiated by a hostile page.
  2. 2. Which defense stops a hostile site because it cannot read your page?

    The same-origin policy keeps the hostile page from reading your forms, so it cannot learn the token.
  3. 3. A server reflects any Origin header and sets Allow-Credentials: true. What is the risk?

    Reflection with credentials effectively disables the same-origin protection for logged-in users.
  4. 4. Does CORS protect your API from curl or a server-side script?

    CORS controls what browser scripts may read. It is not authentication or authorization.
  5. 5. Which cookie attribute blocks most cross-site POSTs from carrying the cookie?

    SameSite restricts when the browser sends the cookie on cross-site requests.

Summary

  • CSRF abuses automatic cookie sending to make logged-in users trigger actions; it targets state-changing requests.
  • Combine SameSite cookies, anti-CSRF tokens, Origin checks and correct HTTP methods.
  • The same-origin policy blocks cross-origin reads; CORS relaxes it deliberately and is not an authentication control.
  • Use exact allow-lists for CORS, never * or reflected origins with credentials.
  • Add framing protection with frame-ancestors to stop clickjacking.

Next: Cryptographic Failures: Protecting Data (A02)