CSRF Works Because Browsers Attach Cookies to Requests Other Sites Trigger

In progress AppSec Django

A cookie is a small piece of data a site asks the browser to store and send back with every later request to that site: it keeps a cart between pages or a user logged in. The browser sends it even when another site caused the request. Cross-site request forgery (CSRF) abuses exactly that: a page on evil.example submits a hidden form to bank.example/transfer, the browser adds the victim's session cookie, and the bank sees an authenticated request it never meant to accept.

Why the Server Can't Tell by Default

The forged request has the right URL, the right method and a valid session cookie. Nothing in a cookie says which site started the request. The defence must add something the attacker's page can't know or can't send.

Defences

  1. A CSRF token in every state-changing form: a secret value tied to the user's session that the server checks on POST. The attacker's page can make the browser send the cookie but can't read the token from another origin.
  2. SameSite cookies: SameSite=Lax (the default in modern browsers when the attribute is missing) stops the cookie from being sent on cross-site POST requests; Strict blocks it on every cross-site request.
  3. Safe methods stay safe: GET must never change state, since links and images can trigger it from anywhere.

In Django

CsrfViewMiddleware is enabled by default and rejects unsafe requests without a valid token. Templates add it to forms:

<form method="post">
  {% csrf_token %}
  {{ form }}
  <button type="submit">Create</button>
</form>

JavaScript clients read the csrftoken cookie and send it in the X-CSRFToken header.

References

Review cards

Flashcard Why does a CSRF token stop a forged form post?

It's a secret tied to the session, checked on unsafe requests. The attacker's page can make the browser send the cookie, but can't read the token from another origin.

Quiz How does a Django template add the CSRF token to a POST form?
  • {% csrf_token %} inside the <form>
  • {{ csrf_token }} as plain text in the form
  • @csrf_exempt on the view
  • Nothing: CsrfViewMiddleware adds it to forms

The tag renders a hidden input with the token. The middleware only checks it, and csrf_exempt turns the protection off. JavaScript clients send it in the X-CSRFToken header.