Common causes of CSRF errors in Django
We’ve all been there, busy beavering away on a Django site when suddenly you’re getting reports of a form that’s failing to submit. Whether it’s login, signup, password reset or something custom you’ve cooked up, it doesn’t appear to be working. After some back and forth, you get a screenshot of the following:
A good place to start if you’re unfamiliar with CSRF (Cross Site Request Forgery) attacks and what tools Django has to mitigate these is by looking at the docs. These explain:
This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser.
It goes on to describe Django’s implementation is based on the following 5 points:
- A CSRF cookie that is a random secret value other sites won’t have access to.
- A hidden form field (csrfmiddlewaretoken) present in all outgoing POST forms (see
{% csrftoken %}
template tag. - All incoming requests that are not of a safe HTTP type ie. POST must contain a CSRF cookie and the csrfmiddlewaretoken. If not, the user will get a 403 error.
- CsrfViewMiddleware verifies the origin header if provided by the browser…