gpt4 book ai didi

Django @login_required 删除 https

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:36 24 4
gpt4 key购买 nike

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

但是,每当我使用 https 时,重定向都会以某种方式断开安全连接,所以我得到类似 https://cumulus.dev/locker -> http://cumulus.dev/locker/login?next =/储物柜

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

我使用 Nginx 来处理 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 看到配置的 header 时,它会将请求视为 HTTPS 而不是 HTTP:request.is_secure() 将返回 true,将生成 https:// URL,等等。

但是,请注意文档中的安全警告:您必须确保代理从所有传入的客户端请求(包括 HTTP 和 HTTPS)中替换或删除受信任的 header 。您上面的 nginx 配置不会使用 X-Forwarded-Ssl 执行此操作,使其可被欺骗。

对此的常规解决方案是在每个代理中根据需要将 X-Forwarded-Protocol 设置为 httphttps配置。然后,您可以配置 Django 以使用以下方式查找它:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

关于Django @login_required 删除 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com