Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Django form POST returns 403 Forbidden: CSRF verification failed

ErrorForbidden (403)

Short answer

Django rejects an unsafe request when the CSRF cookie or the form token is missing or wrong, or when the Origin or Referer check fails. The reason text on the 403 page and the django.security.csrf log line tell you which. Common fixes: add {% csrf_token %} to the form, list your HTTPS origin in CSRF_TRUSTED_ORIGINS, and reload the form after login.

  • Applies to Django 4.2 LTS, 5.2 LTS, Python 3.12, Gunicorn behind nginx
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Read the reason line. Django prints it on the 403 page when DEBUG is on, and logs a warning to the django.security.csrf logger always.

    grep -R 'django.security.csrf\|CSRF' /var/log/gunicorn/ /var/log/app/ 2>/dev/null | tail -n 20
  2. 2Match what you see, then jump to its fix

    1. 1Reason says the CSRF token is missing or incorrect, and the HTML of the form has no csrfmiddlewaretoken fieldThe form has no CSRF tokenFix
    2. 2The reason line mentions the Origin check, and the form is served over HTTPS from a host that is not in CSRF_TRUSTED_ORIGINSOrigin checking failed behind an HTTPS proxy or on another host nameFix
    3. 3The reason line mentions the Referer check, and the POST goes to an HTTPS URL from a page with a no-referrer policyThe Referer header is stripped on an HTTPS siteFix
    4. 4Reason says the CSRF cookie is not set, and the browser's cookie list has no csrftoken for the siteThe CSRF cookie is never stored or is not sent backFix
    5. 5Fails only after signing in, or after using the back buttonThe form was loaded before login or logoutFix

What does the error look like?

  • Forbidden (403)
  • CSRF verification failed. Request aborted.

Cause 1 of 5

The form has no CSRF token

1Check

Unsafe methods (POST, PUT, PATCH, DELETE) need the csrfmiddlewaretoken form field and the CSRF cookie. View the page source of the form.

curl -s -c /tmp/jar https://app.example.com/contact/ | grep -i csrfmiddlewaretoken

2Fix

Put the template tag inside every POST form that posts to your own site. Do not put it in forms that post to other domains.

<form method="post" action="/contact/">
  {% csrf_token %}
  <input name="email">
  <button type="submit">Send</button>
</form>

3Verify

The rendered HTML now has a hidden csrfmiddlewaretoken input and the POST returns 200 or a redirect.

curl -s -c /tmp/jar https://app.example.com/contact/ | grep -c csrfmiddlewaretoken

Confirmed by docs.djangoproject.com

Did this fix it?

Cause 2 of 5

Origin checking failed behind an HTTPS proxy or on another host name

1Check

Django requires the Origin header to match the Host origin. Behind a proxy that terminates TLS, Django may see plain HTTP and build a different origin, so a form served from https://app.example.com fails.

python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_TRUSTED_ORIGINS, s.SECURE_PROXY_SSL_HEADER, s.ALLOWED_HOSTS)"

2Fix

Add each public origin, with its scheme, to CSRF_TRUSTED_ORIGINS. If a proxy sets X-Forwarded-Proto, and only if it strips that header from incoming requests, tell Django to trust it.

# settings.py
CSRF_TRUSTED_ORIGINS = ["https://app.example.com", "https://*.example.com"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

3Verify

Restart the app and repeat the POST from the browser.

sudo systemctl restart gunicorn

Confirmed by docs.djangoproject.com

Did this fix it?

Cause 3 of 5

The Referer header is stripped on an HTTPS site

1Check

Over HTTPS, a request without an Origin header needs a matching Referer. A page with Referrer-Policy: no-referrer (or a meta referrer tag) removes it.

curl -sI https://app.example.com/contact/ | grep -i referrer-policy
grep -R "no-referrer" templates/ 2>/dev/null

2Fix

Stop sending no-referrer on pages that POST to your own site. Use rel="noreferrer" on links to third-party sites instead.

<meta name="referrer" content="same-origin">
<a href="https://other.example.net" rel="noreferrer">partner</a>

3Verify

Reload the form and submit it; the 403 is gone.

curl -sI https://app.example.com/contact/ | grep -i referrer-policy

Confirmed by docs.djangoproject.com

Did this fix it?

Cause 4 of 5

The CSRF cookie is never stored or is not sent back

1Check

A cookie marked Secure is only sent over HTTPS, so CSRF_COOKIE_SECURE = True on a plain HTTP development server breaks every POST. Cookies blocked by the browser, or a CSRF_COOKIE_DOMAIN that does not cover the host, have the same effect.

python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_COOKIE_SECURE, s.CSRF_COOKIE_DOMAIN, s.CSRF_COOKIE_SAMESITE)"

2Fix

Serve the site over HTTPS, or set CSRF_COOKIE_SECURE to False only in local development. Set CSRF_COOKIE_DOMAIN to None or a domain that covers the page.

# settings_dev.py
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_DOMAIN = None

3Verify

The csrftoken cookie appears in the browser's storage after loading the form.

curl -s -D - -o /dev/null http://localhost:8000/contact/ | grep -i set-cookie

Confirmed by docs.djangoproject.com

Did this fix it?

Cause 5 of 5

The form was loaded before login or logout

1Check

Django rotates CSRF tokens at login. A form rendered earlier still holds the old token.

# Reproduce: open the form, sign in from another tab, then submit the first tab

2Fix

Reload the page to get a fresh token. For pages that stay open a long time, show a message that asks the user to refresh.

# no code change needed; reload the form page before submitting

3Verify

A form loaded after login submits successfully.

# Submit the freshly loaded form

Confirmed by docs.djangoproject.com

Did this fix it?

How do I stop it coming back?

  • Keep CsrfViewMiddleware in MIDDLEWARE and never use @csrf_exempt to silence an error.
  • Set CSRF_TRUSTED_ORIGINS with the scheme in every environment that has its own host name.
  • Test one real form POST over HTTPS in staging after every proxy or domain change.
  • Set CSRF_FAILURE_VIEW to a page that tells users to reload.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

CodeIgniter works locally but every page is 404 on the live server

The requested URL was not found on this server.

A 404 on the live server comes from one of four places: the document root is not the public folder, Apache ignores .htaccess or nginx has no try_files rule, the route is not defined because auto routing is off, or the controller file name differs from its class in case.

5 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.