每当我尝试登录 Django 的管理应用程序时,在填写用户名和密码并提交表单后,页面永远挂起。
当我在浏览器中刷新 POST 请求时,我得到:
CSRF verification failed. Request aborted.
当我再次刷新页面时,一切正常,我看到管理应用程序,我已登录,我可以在我的应用程序和表上执行 CRUD 操作。
任何想法为什么?
我在 Django 应用程序前面有 Nginx 反向代理进行 https 握手。所以当你去(例子)时:
https://platform.staging.com/admin/
Nginx 反向代理到
http://admin1.staging.platform.com/admin/
这是我的 nginx 配置:
upstream admin-cluster {
ip_hash;
server admin1.staging.platform.com;
}
# force redirect of http to https
# application will be available only over https
server {
listen 80 default;
server_name platform.staging.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
# https server
# traffic is going to local web servers over normal http
# front nginx proxy server will hold ssl session
server {
listen 443 ssl spdy;
server_name platform.staging.com;
keepalive_timeout 70;
ssl on;
ssl_certificate /etc/ssl/platform.staging.com.crt;
ssl_certificate_key /etc/ssl/platform.staging.com.key;
location /admin {
proxy_pass http://admin-cluster;
}
}
编辑:
所以,我找到了一个解决方法。当我在 Nginx 反向代理上也允许端口 80 但将所有 http 请求重定向到 https 时,如下所示:
server {
listen 80 default;
server_name platform.staging.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
它解决了这个问题。知道为什么吗?
最佳答案
检查覆盖 SESSION_COOKIE_SECURE
的值的设置和 CSRF_COOKIE_SECURE
值,因为问题可能与 CSRF cookie 有关。 编辑 : 事实上,我已经将这两个值设置为 True。
另外,请检查您的 SECURE_PROXY_SSL_HEADER
设置,虽然我不确定它与您的问题有关。我在您的 nginx conf 文件中缺少一个 proxy_set_header X-Forwarded-Protocol 指令,用于让 Django 知道您正在通过代理。
关于Django Admin - CSRF 验证失败。请求中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21135103/