Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Forbidden (403) CSRF verification failed. Request aborted. — Django after deploy

Forbidden (403) CSRF verification failed. Request aborted. means Django's CSRF middleware refused a POST. Right after moving behind HTTPS and a proxy, the usual reason is Origin checking failed: add the site's origin with its scheme, such as https://example.com, to CSRF_TRUSTED_ORIGINS. For CSRF cookie not set or CSRF token missing, put the csrf_token tag in the form or send the X-CSRFToken header.

By Livops team, the people who build and run LivopsUpdated

What the visitor sees, in production with DEBUG off[6][7]:

Forbidden (403)
CSRF verification failed. Request aborted.

More information is available with DEBUG=True.

The reason is in one of these lines, which Django logs, or shows under “Reason given for failure” when DEBUG is on[5][7]:

Forbidden (Origin checking failed - https://shop.example.com does not match any trusted origins.): /accounts/login/
Forbidden (CSRF cookie not set.): /accounts/login/
Forbidden (CSRF token missing.): /api/orders/

This page explains the checks behind the error, gives the fix for each reason, from the one that appears on the first deploy behind HTTPS, and shows how to test the fix before deploying again.

What does the error mean?

Django’s CsrfViewMiddleware checks every request that is not GET, HEAD, OPTIONS or TRACE[1]. It checks, in this order[5]:

  1. The Origin header, if the browser sent one. It must equal the scheme and host Django thinks it is serving, https if request.is_secure() is true and http if not, or match an entry of CSRF_TRUSTED_ORIGINS[5].
  2. The Referer header, for HTTPS requests that arrived without Origin. Django does strict referer checking on them[1].
  3. The cookie and the token. The csrftoken cookie must be present, and the token must come in the form field csrfmiddlewaretoken or, failing that, in the X-CSRFToken header[5].

The first check that fails ends the request with a 403[1]. With DEBUG off, the page leaves the reason out[7], and Django’s default logging sends its messages to the console only when DEBUG is on[8]. To see the reason in your logs, send the CSRF logger to the console:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"csrf_console": {"class": "logging.StreamHandler"}},
    "loggers": {
        "django.security.csrf": {"handlers": ["csrf_console"], "level": "WARNING", "propagate": False},
    },
}

Causes, most common first

1. Origin checking failed, behind HTTPS

Origin checking failed - https://shop.example.com does not match any trusted origins.

This is the one that appears after the first deploy. The browser posts the form from https://shop.example.com and says so in Origin. A platform or a reverse proxy takes the HTTPS connection and passes the request on to Django over plain HTTP, and then is_secure() returns False even for requests the visitor made over HTTPS[3]. Django builds the origin it expects as http://shop.example.com, the two strings differ, and the POST is refused[5]. Locally everything is http://, so you never see it there. The admin login is usually the first form to fail.

Fix: list the origins in CSRF_TRUSTED_ORIGINS. The setting is the list of trusted origins for unsafe requests, and it accepts subdomain wildcards such as https://*.example.com[3]. Since Django 4.0 each value must include the scheme, and a value that started with a dot is now written with an asterisk: .example.com becomes https://*.example.com[4].

CSRF_TRUSTED_ORIGINS = ["https://shop.example.com", "https://www.shop.example.com"]

An entry without a wildcard is compared with the Origin header as a whole string[5], so write it the way a browser sends it: scheme and host, a port only if the address has one, no path and no trailing slash. To keep one list of domains, build the origins from ALLOWED_HOSTS, turning a leading dot into a wildcard:

CSRF_TRUSTED_ORIGINS = [
    "https://" + ("*" + host if host.startswith(".") else host)
    for host in ALLOWED_HOSTS
    if host and host != "*"
]

The other fix: tell Django the request was HTTPS. SECURE_PROXY_SSL_HEADER makes is_secure() trust a header from your proxy, usually ("HTTP_X_FORWARDED_PROTO", "https"), and then the origin matches without being listed[3]. Django’s warning is explicit: set it only if your app is behind a proxy that strips X-Forwarded-Proto from incoming requests and sets it only for requests that came in over HTTPS; otherwise keep it None[3]. A forged header would make plain HTTP look secure. The same setting is the cure when SECURE_SSL_REDIRECT = True causes an endless redirect behind a proxy[3]. Once requests count as secure, those without an Origin header also go through the strict Referer check[1].

CSRF cookie not set.

The POST arrived without the csrftoken cookie[5]. This is the one reason the production 403 page explains by itself, with a note that the site needs a CSRF cookie to accept forms[7]. The usual causes:

  • CSRF_COOKIE_SECURE = True on plain HTTP. A secure cookie may be sent by browsers only over HTTPS[3]. Turn it on once the site is on HTTPS, as the deployment checklist says[9], but not for a test over http://. Tie it to the environment: CSRF_COOKIE_SECURE = not DEBUG.
  • The page never set the cookie. Django sets it when a template uses the csrf_token tag. A page that adds its forms with JavaScript, or one that posts with AJAX and has no form, may get no cookie; put ensure_csrf_cookie on the view that sends the page[2].
  • The form is on another site. The cookie’s SameSite flag is Lax by default, which keeps it out of cross-site requests[3]. A form on another domain, or your page inside someone else’s frame, posts without it.

3. CSRF token missing

CSRF token missing.

The cookie arrived, but neither the form field nor the header did[5]. In a template, every POST form to your own site needs the tag; never put it in a form that posts to an external URL, because that leaks the token[2]:

<form method="post">
  {% csrf_token %}
  ...
</form>

For fetch or another AJAX request, send the token in the X-CSRFToken header[2]. Read it from the csrftoken cookie; if CSRF_COOKIE_HTTPONLY or CSRF_USE_SESSIONS is on, render the csrf_token tag and read the hidden field from the page instead[2]:

const csrftoken = document.cookie
  .split("; ")
  .find((c) => c.startsWith("csrftoken="))
  ?.split("=")[1];

fetch("/api/orders/", {
  method: "POST",
  headers: { "X-CSRFToken": csrftoken, "Content-Type": "application/json" },
  body: JSON.stringify(order),
  mode: "same-origin", // do not send the token to another domain
});

If your client uses another header name, CSRF_HEADER_NAME must name it in request.META form: X-XSRF-TOKEN becomes HTTP_X_XSRF_TOKEN[3].

4. CSRF token from POST incorrect

A token arrived but does not match the cookie. For a header the message reads CSRF token from the 'X-Csrftoken' HTTP header incorrect.[5] Two usual causes: the token is rotated at login, so a form opened before logging in elsewhere, or reached with the back button after a login, is stale[7]; and a view cached with cache_page that was cached without its CSRF cookie, which csrf_protect under the cache decorator prevents[2].

5. Referer checking failed - no Referer

An HTTPS request with no Origin and no Referer. Strict referer checking needs the header, so a Referrer-Policy: no-referrer header or <meta name="referrer" content="no-referrer"> breaks the form; use rel="noreferrer" on links to other sites instead[1][7].

How to confirm the fix locally

Run with production settings and post the way the browser will, with an HTTPS origin, to a form view:

DEBUG=1 ALLOWED_HOSTS=shop.example.com python manage.py runserver 127.0.0.1:8000
curl -s -X POST -H "Host: shop.example.com" -H "Origin: https://shop.example.com" \
  http://127.0.0.1:8000/accounts/login/ | grep -A 3 "Reason given"

Before the fix the reason is Origin checking failed. After adding https://shop.example.com to CSRF_TRUSTED_ORIGINS it becomes CSRF cookie not set.: curl sent no cookie, so this is the expected next check[5], and the origin is now trusted. This assumes your settings read DEBUG and ALLOWED_HOSTS from the environment. python manage.py check --deploy, run against the production settings, automates some of the deployment checklist, the list that also asks for CSRF_COOKIE_SECURE[9].

On Livops

  • Every address is HTTPS. The project’s <name>.livops.app address gets HTTPS automatically, and a domain you connect gets its certificate as soon as it is live. Your app itself listens on the port in PORT; there is no certificate to set up in Django.
  • ALLOWED_HOSTS is set for you. For a Python web app, Livops sets the ALLOWED_HOSTS variable to the project’s addresses, comma-separated, unless you set it yourself. Read it in settings.py, and build CSRF_TRUSTED_ORIGINS from it as in cause 1; if you set ALLOWED_HOSTS=.livops.app yourself, the same lines turn it into https://*.livops.app.
  • SECURE_PROXY_SSL_HEADER only on evidence. Set it only after you have checked which header reaches your app and that a visitor cannot forge it, as Django’s warning asks. CSRF_TRUSTED_ORIGINS does not depend on any header.
  • Settings from Variables. Put SECRET_KEY and DEBUG in the service’s Variables, and deploy again after changing them.
  • The reason in Logs. With the LOGGING lines above, each refused POST prints its reason on the project’s Logs page.

What Livops does for Django: Frameworks. The check that comes before this one: DisallowedHost: Invalid HTTP_HOST header. The whole production setup: Django hosting.

Questions

Why do forms work locally and fail with a CSRF error after deploy?

Locally the browser and Django both see http://127.0.0.1:8000, so the Origin header matches. In production the browser sends https://your-domain, while Django behind a proxy may see the request as plain HTTP and expect http://your-domain. The two differ, and the POST is refused.

Does CSRF_TRUSTED_ORIGINS need https:// in it?

Yes. Since Django 4.0 every value must include the scheme, for example https://example.com, and a value for all subdomains is written https://*.example.com instead of .example.com.

Should I set SECURE_PROXY_SSL_HEADER or CSRF_TRUSTED_ORIGINS?

CSRF_TRUSTED_ORIGINS is the safe first fix: it depends on nothing but your domain list. SECURE_PROXY_SSL_HEADER is right only if your proxy sets the header for HTTPS requests and strips it from incoming ones; Django warns that setting it otherwise can compromise the site.

Why does the 403 page not say what went wrong?

With DEBUG off, Django's page shows only the general message; the reason is printed only when DEBUG is True. Django's default logging also sends its messages to the console only with DEBUG on, so add a logger for django.security.csrf to see the reason in your logs.

I added CSRF_TRUSTED_ORIGINS and now see CSRF cookie not set. Is that progress?

Yes. The origin check passed, and Django moved on to the next one. Check that the page with the form sets the cookie, and that CSRF_COOKIE_SECURE is not on while you test over plain http.

Can I just add csrf_exempt to the view?

Only for a view that really takes no browser session, such as a webhook that checks its own signature. On a login form or the admin it removes the protection instead of fixing the configuration.

What does Livops set up for Django?

It sets the ALLOWED_HOSTS variable to the project's addresses unless you set it yourself, runs migrate before every start and collectstatic during the build when STATIC_ROOT is set. Every address is served over HTTPS.

Sources

  1. Django docs — Cross Site Request Forgery protection (docs.djangoproject.com). Checked .
  2. Django docs — How to use Django's CSRF protection (docs.djangoproject.com). Checked .
  3. Django docs — Settings (docs.djangoproject.com). Checked .
  4. Django docs — Django 4.0 release notes (docs.djangoproject.com). Checked .
  5. Django source — django/middleware/csrf.py (6.1) (raw.githubusercontent.com). Checked .
  6. Django source — django/views/csrf.py (6.1) (raw.githubusercontent.com). Checked .
  7. Django source — django/views/templates/csrf_403.html (6.1) (raw.githubusercontent.com). Checked .
  8. Django docs — Logging (docs.djangoproject.com). Checked .
  9. Django docs — Deployment checklist (docs.djangoproject.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Django app

Got a question? — @livops_uz