It might be useful to add a note or warning below
https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-
CSRF_TRUSTED_ORIGINS explaining that it should only be neccessary to
configure this if you are actually making requests across subdomains, and
in other cases setting up SECURE_PROXY_SSL_HEADER might be a more
appropriate solution (as long as the proxy correctly sets a header like X
-Forwarded-Proto).
I ran into this problem when I updated a project hosted behind AWS ELB
load balancer and gunicorn to Django 4.0, and the CSRF origin checking for
the Django admin stopped working in a staging environment, with the
message `CSRF verification failed. Request aborted.`. I could not figure
out what was going on using the documentation and ended up finding the
root cause through a stackoverflow answer which pointed out that the
origin header is compared against a string constructed of the host,
prefixed by either http or https based on the result of
''request.is_secure()''
- https://stackoverflow.com/a/71482883
In my case, the proxy setup was forwarding requests over HTTP, so
is_secure() was false and CSRF was comparing the origin `https://subdomain
.my-domain.com` against "host" `http://subdomain.my-domain.com`. It seems
like the best solution here is to use SECURE_PROXY_SSL_HEADER to allow
Django to determine if the client is using HTTPS or not, and use the
"host" string `https://subdomain.my-domain.com` . Looking at the
referenced stackoverflow thread, this is a recurring problem for users
updating to Django 4.0 and many end up with the sub-optimal solution of
adding the origin with https to CSRF_ALLOWED_ORIGINS explicitly.
--
Ticket URL: <https://code.djangoproject.com/ticket/34855>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.