Nginx + gunicorn Django 1.9 CSRF验证失败

时间:2016-07-15 08:27:24

标签: 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;

}

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')

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

更新#1
通过 Chrome Incognito 模式,一切正常!

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

错误

2 个答案:

答案 0 :(得分:2)

我在没有Cloudflare的可比设置中遇到了同样的错误:Nginx - &gt; Gunicorn - &gt; Django的。

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

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

答案 1 :(得分:1)

在命名http-header时,您似乎犯了一个错误。您必须确保 X-Forwarded-Proto 标头的名称在以下两者中都是正确的: nginx 配置和 Django &#39; s settings.py。

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

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

这一个:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

或者您可以在下面的行中添加nginx配置文件:

    proxy_set_header X-Forwarded-Protocol https;