Nginx + gunicorn Django 1.9 CSRF 验证失败

Joh*_*ohn 3 python django nginx django-csrf

背景:
我正在尝试使用 django配置 cloudflare灵活SSL。
浏览器 <-HTTPS-> Cloudflare <-HTTP-> Nginx <--> Gunicorn

问题:
我的CSRF 验证失败。管理面板登录请求中止- 目前这是我网站上唯一的 POST 请求。(相信我,我在这里浏览了大量帖子和要点,但似乎没有什么对我有用:()

配置:

Nginx -

listen 80;
server_name domain.com;

real_ip_header X-Forwarded-For;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 199.27.128.0/21;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
real_ip_header CF-Connecting-IP;

location / {
    proxy_pass http://unix:/var/webapps/run/SBWebsite.sock;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}
Run Code Online (Sandbox Code Playgroud)

Django - settings.py

DEBUG = False
PREPEND_WWW = True
USE_X_FORWARDED_HOST = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
Run Code Online (Sandbox Code Playgroud)

Cloudflare DNS -

A domain.com  points to <ip> Automatic
CNAME www is an alias of domain.com Automatic

Page rule is set to always use HTTPS
Run Code Online (Sandbox Code Playgroud)

更新 #1
Chrome 隐身模式下一切正常!

更新 #2(解决方案)
似乎是 cookie 问题,我从浏览器中清除了所有 cookie,现在它工作正常!!
部分也可能是SECURE_PROXY_SSL_HEADER问题,因为它在我的 settings.py 中是错误的

veu*_*ent 5

在没有 Cloudflare 的类似设置中,我遇到了同样的错误:Nginx -> Gunicorn -> Django。

我通过更改此 Nginx 设置
proxy_set_header X-Forwarded-Proto https;
来修复它:为此:
proxy_set_header X-Forwarded-Proto $scheme;

因此该方案不是硬编码的,而是从请求中派生的。


fri*_*ist 1

看来您在命名 http-header 时犯了一个错误。您必须确保X-Forwarded-Proto标头的名称在nginx配置和Django的 settings.py 中都是正确的。

因此,您应该通过替换以下行来修改settings.py文件:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
Run Code Online (Sandbox Code Playgroud)

与这个:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Run Code Online (Sandbox Code Playgroud)

或者您可以将以下行添加到 nginx 配置文件中:

    proxy_set_header X-Forwarded-Protocol https;
Run Code Online (Sandbox Code Playgroud)