I can access Django admin by redirecting traffic from nginx port 80 to django port 8000. However, when I change nginx listen port to 81 I received, after signing in Django admin
Forbidden (403)
CSRF verification failed. Request aborted.
nginx.conf
server {
listen 81;
server_name localhost;
location = /favicon.ico {access_log off;log_not_found off;}
location /static/ {
include /etc/nginx/mime.types;
alias /static/;
}
location / {
proxy_pass http://backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
docker-compose file
version: '3.9'
services:
backend:
image: thequy/resume_builder_django:2.0
build:
context: ./backend
dockerfile: ./docker/django/Dockerfile
env_file:
- .env
command: gunicorn resume_builder.wsgi -w ${GUNICORN_WORKER_COUNT} -b 0.0.0.0:${DJANGO_PORT}
networks:
- resume_builder_network
backend_nginx:
image: thequy/resume_builder_django_nginx:1.0
build: ./backend/docker/nginx
ports:
- "${BACKEND_DJANGO_PORT}:${BACKEND_DJANGO_PORT}"
depends_on:
- backend
networks:
- resume_builder_network
networks:
resume_builder_network:
I have changed BACKEND_DJANGO_PORT=81
.
I tried adding CORS_ALLOW_ALL_ORIGINS=True
and CSRF_TRUSTED_ORIGINS=["http://backend_nginx:81"]
but it doesn't help
Edit: I tried chaning ports of backend_nginx to different values and I realized that the host port must be on port 80, nginx port doesn't matter.
CodePudding user response:
Since Django 4.0, origin checking is added in CSRF middleware as mentioned here https://docs.djangoproject.com/en/4.1/ref/csrf/.
So, if the request generated from a specific domain doesn't match with any trusted origins, it raises Forbidden (403) CSRF verification failed
.
In your case, you need to set following in settings.py
(I assume you are running this locally)
CSRF_TRUSTED_ORIGINS = ["http://localhost:81"]
Now the question arises why it works for 80 port without setting CSRF_TRUSTED_ORIGINS
, I assume the default 80 port is always trusted, however I can't find any documentation of it.