问题
Background
When I try to access into my Django administration panel, I get Forbidden (403) CSRF verification failed. Request aborted.
, even if I disable the CSRF middleware. This affects all users, in different locations with different browsers. I've followed the steps to fix this error of several questions in stackoverflow, but still the same. This has been killing me for weeks.
Issue
I'm using https with Cloudflare (Free plan), but this error persist if I deactivate https. This occurs in mydomain.com/admin
Known facts
- I'm using Django 2.0 and gunicorn 19.0
- I've checked the cookies of my browser
- I've tried removing
django.middleware.csrf.CsrfViewMiddleware
- This occurs just in the Django Admin dashboard, when CSRF middleware is enabled, the another POST or GET forms works fine.
- I'm logged into my Django Admin dashboard, and if I logout, I can login again with no problems, but if I try from another place, or with another user, the problem occurs again.
- Gunicorn config it's the default.
Configuration files
Settings.py
CSRF_TRUSTED_ORIGINS = ['.domain.com']
CSRF_COOKIE_DOMAIN = ['.domain.com', '127.0.0.1']
CSRF_COOKIE_SECURE = True
ALLOWED_HOSTS = ['127.0.0.1', 'domain.com', 'www.domain.com', '104.336.44.153', '.domain.com']
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Nginx
server {
server_name domain.com;
access_log off;
location /static {
alias /opt/myenv/myenv/static/;
}
location /descargas/dir/ {
alias /opt/myenv/myenv/dir/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
Please help! Thanks for reading.
回答1:
The CSRF cookie is set by CsrfViewMiddleware
, so you should keep it.
I would try to change your MIDDLEWARE
ordering:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', # THE FIRST
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
来源:https://stackoverflow.com/questions/51853797/weird-csrf-error-in-django-with-nginx-and-gunicorn