背景
当我尝试访问Django管理面板时,即使禁用CSRF中间件,我也会得到Forbidden (403) CSRF verification failed. Request aborted.
。这会影响使用不同浏览器的不同位置中的所有用户。我已经按照步骤修复了stackoverflow中几个问题的错误,但仍然相同。这已经杀死我好几个星期了。
问题
我在Cloudflare(免费计划)中使用https,但是如果停用https,此错误仍然存在。这发生在mydomain.com/admin
已知事实
django.middleware.csrf.CsrfViewMiddleware
配置文件
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"';
}
}
请帮助!谢谢阅读。
答案 0 :(得分:0)
CSRF cookie由CsrfViewMiddleware
设置,因此您应该保留它。
我会尝试更改您的MIDDLEWARE
的顺序:
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',
]