Opened 15 months ago
Closed 15 months ago
#34888 closed Bug (needsinfo)
CSRF verification failed in django 4 when nginx serves the webserver
Reported by: | Muhammad Fazel Samarghandi | Owned by: | nobody |
---|---|---|---|
Component: | CSRF | Version: | 4.2 |
Severity: | Normal | Keywords: | csrf |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Hi there
I just created a very simple project and dockerize it with docker-compose:
version: "3.8" services: backend: build: context: . command: > /bin/sh -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 expose: - 8000 proxy: image: nginx volumes: - type: bind source: ./proxy/nginx.conf target: /etc/nginx/conf.d/default.conf read_only: true ports: - 80:80 depends_on: - backend
And this is the proxy/nginx.conf:
server { listen 80; server_name localhost; location / { proxy_pass http://backend:8000; proxy_http_version 1.1; } }
And the Dockerfile:
FROM python:3 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . .
There is Django==4.2.5 in requirements.txt and django itself is just super basic and just ALLOWED_HOSTS sets to all.
By running the docker-compose the django can be accessed from port 8000 and 80 by nginx.
The problem is when going to admin panel and send a post request to login, it returns
Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed - http://127.0.0.1 does not match any trusted origins.
and it can't go away with any trick. I also get this in drf and i tried adding CSRF_TRUSTED_ORIGINS
,
CORS_ALLOWED_ORIGINS
and even commented the csrf middleware, but nothing changed.
As soon as i changed the django version to 3.2 the error is fixed
You've not explained why Django is at fault. Perhaps the CSRF_TRUSTED_ORIGINS changes in Django 4.0 are relevant. See TicketClosingReasons/UseSupportChannels if you need help debugging your issue, and reopen if you can explain why Django is at fault.