Django@login_需要删除https



我正在尝试使用SSL在本地测试我的Django应用程序。我有一个带有@login_required装饰器的视图。所以当我点击/locker时,我会被重定向到/locker/login?next=/locker。这适用于http。

然而,每当我使用https时,重定向会以某种方式断开安全连接,所以我得到了类似https://cumulus.dev/locker -> http://cumulus.dev/locker/login?next=/locker 的东西

如果我直接转到https://cumulus.dev/locker/login?next=locker,页面会通过安全连接打开。但一旦我输入了用户名和密码,我就会返回到http://cumulus.dev/locker

我使用Nginx来处理SSL,然后SSL与runserver进行通信。我的nginx配置是

upstream app_server_djangoapp {
server localhost:8000 fail_timeout=0;
}
server {
listen 80;
server_name cumulus.dev;
access_log  /var/log/nginx/cumulus-dev-access.log;
error_log  /var/log/nginx/cumulus-dev-error.log info;
keepalive_timeout 5;
# path for static files
root /home/gaurav/www/Cumulus/cumulus_lightbox/static;
location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    if (!-f $request_filename) {
        proxy_pass http://app_server_djangoapp;
        break;
    }
}
}
server {
listen 443;
server_name cumulus.dev;
ssl on;
ssl_certificate /etc/ssl/cacert-cumulus.pem;
ssl_certificate_key /etc/ssl/privkey.pem;
access_log  /var/log/nginx/cumulus-dev-access.log;
error_log  /var/log/nginx/cumulus-dev-error.log info;
keepalive_timeout 5;
# path for static files
root /home/gaurav/www/Cumulus/cumulus_lightbox/static;
location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Ssl on;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    if (!-f $request_filename) {
        proxy_pass http://app_server_djangoapp;
        break;
    }
}
}

Django仅在代理后面的纯HTTP上运行,因此它将始终使用它来构造绝对URL(如重定向),除非您配置它如何查看代理请求最初是通过HTTPS发出的。

从Django 1.4开始,您可以使用SECURE_PROXY_SSL_HEADER设置来实现这一点。当Django看到配置的头时,它会将请求视为HTTPS而不是HTTP:request.is_secure()将返回true,https:// URL将生成,依此类推

但是,请注意文档中的安全警告:必须确保代理从所有传入的客户端请求(包括HTTP和HTTPS)中替换或删除受信任的标头。你上面的nginx配置在X-Forwarded-Ssl上没有做到这一点,这使得它可以被欺骗。

常规的解决方案是在每个代理配置中将X-Forwarded-Protocol设置为httphttps(视情况而定)。然后,您可以配置Django来查找它,使用:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

最新更新