【问题标题】:Nginx, SSL, Django, CSRF verification failed (custom port)Nginx、SSL、Django、CSRF 验证失败(自定义端口)
【发布时间】:2015-11-23 02:12:54
【问题描述】:

我正在开发一个使用 Django、nginx 和 Gunicorn 的项目。一切都很好,除了 POST 请求。 Django 引发 CSRF 错误。 我不知道我的 django 和/或 nginx 配置中有什么缺失或错误。

编辑:我发现了问题所在。因为我的异国 SSL 端口。 我在“位置/”块中替换了这一行:

proxy_set_header   Host $host;

作者:

proxy_set_header   Host localhost:8443;  

Django 错误:

Forbidden (403):
CSRF verification failed. Request aborted.

Reason given for failure:
Referer checking failed - https://localhost:8443/accounts/login/ does not match https://localhost/

这是我的 nginx 配置文件:

server {
    listen       8880;
    server_name  localhost:8443;

    rewrite        ^ https://$server_name$request_uri? permanent;
}

#Gunicorn
upstream project {
    server localhost:8888;
}

# HTTPS server
server {
    listen       8443 ssl default_server;
    ssl          on;
    server_name  localhost;

    ssl_certificate      /path/file.crt;
    ssl_certificate_key  /path/file.key;

    #Disable SSLv3
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_session_cache    shared:SSL:10m;
    ssl_session_timeout  10m;

    ssl_ciphers  "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";
    ssl_prefer_server_ciphers  on;
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";


    location / {
      proxy_pass         http://localhost:8888;
      proxy_set_header   X-Real-IP $remote_addr;
      proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Ssl https;
      proxy_set_header   X-Forwarded-Proto https;
      proxy_set_header   X-Forwarded-Port 8443;
      proxy_set_header   Host $host; #Replaced by proxy_set_header   Host localhost:8443;
    }
}

在我的 settings.py 中:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

【问题讨论】:

  • 如果解决了您的问题,请接受任何答案,或者自己编写解决方案作为答案并接受。谢谢! :)

标签: django ssl nginx


【解决方案1】:

尝试添加您的location / 这个:proxy_pass_header X-CSRFToken;

【讨论】:

    猜你喜欢
    • 2016-11-18
    • 2012-09-08
    • 2015-06-02
    • 1970-01-01
    • 2018-04-08
    • 2017-03-29
    相关资源
    最近更新 更多