liveBook · Manning

Cross-site request forgery

As explained in Django in Action

Cross-site request forgery is a web attack that tricks an authenticated user’s browser into submitting an unintended state-changing request to a site.

Cross-site request forgery (CSRF) tricks a user into submitting an unintended action to a site where they are already signed in. A malicious site can imitate an ordinary form while quietly changing something important on the real site, such as the user’s password. section 7.1.2

Django blocks this request-forgery pattern with the {% csrf_token %} template tag and CsrfViewMiddleware. The middleware creates a session cookie containing a random value. The tag places a variation of that value in the form as a hidden field. When the form is submitted, Django checks that the token exists and matches the session value; otherwise, it rejects the POST. section 7.1.2

A forged password form

Imagine a malicious page styled like a harmless comment form. Its hidden fields actually request a password change on the real site. The user clicks Submit, and the browser sends the request. A legitimate Django form includes {% csrf_token %}; the attacker’s form cannot know the required token value, so Django rejects the forged POST. section 7.1.2

A protected Django form follows this request flow:

  • Render the form with {% csrf_token %}, adding the hidden protection field. section 7.1.2
  • Submit the form as a POST, sending the hidden token alongside the user’s data. section 7.1.2 section 7.6
  • Let CsrfViewMiddleware compare the submitted token with the value stored in the session cookie. section 7.1.2
  • Continue only when the values match; reject the POST when the token is missing or incorrect. section 7.1.2

How Django in Action covers it

How deep it goes
Explains the attack, token flow, middleware check, and rejection condition without detailing middleware internals.
Examples
Uses a malicious comment-like form whose hidden fields secretly request a password change.
What it assumes
Assumes basic HTML form submission and POST requests while explaining the attack and protection mechanism directly.
What you can do after
Apply it via Django’s {% csrf_token %} tag so submitted forms carry a value Django can validate.
How it connects
Connects CSRF with Django forms, template tags, middleware, session cookies, hidden fields, and HTTP POST requests.

Also explained in

Compare how 5 books explain cross-site request forgery →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.