如何在 Django-auth 生成的页面中启用 https?

2024-01-20

使用Django-auth https://docs.djangoproject.com/en/1.3/topics/auth/应用程序(Django 版本 1.3),我想让我的登录页面转到https://mysite.com/login/。目前,我正在使用:

# urls.py
from django.contrib.auth.views import login
urlpatterns = patterns('', url(r'^login/$', login, name='login-view'),)

# navbar.html
<li id="nav-login"><a href="{% url login-view %}" ><b>Login</b></a></li>

效果很好,但是去http://mysite.com/login/.

当 Django-auth 反转视图名称时,有什么方法可以告诉它使用什么前缀(https)?我已经阅读了整个手册页,但没有找到任何涵盖它的内容。或者也许有某种方式可以告诉url https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#url标签转到https?

或者是手动指定整个 URL 的唯一选项?我希望不会:) 考虑到 Django 到目前为止有多强大,我不敢相信它没有这种能力 - 我一定是忽略了它。 :)


将操作系统环境变量 HTTPS 设置为 on

您需要启用操作系统环境变量HTTPS to 'on'所以 django 会在完全生成的链接前面添加 https(例如,像HttpRedirectRequests)。如果您使用 mod_wsgi,则可以添加以下行:

os.environ['HTTPS'] = "on"

to your wsgi脚本 http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango。您可以通过阅读了解这样做的必要性django/http/__init__.py:

def build_absolute_uri(self, location=None):
    """
    Builds an absolute URI from the location and the variables available in
    this request. If no location is specified, the absolute URI is built on
    ``request.get_full_path()``.
    """
    if not location:
        location = self.get_full_path()
    if not absolute_http_url_re.match(location):
        current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
                                     self.get_host(), self.path)
        location = urljoin(current_uri, location)
    return iri_to_uri(location)

def is_secure(self):
    return os.environ.get("HTTPS") == "on"

保护您的 cookie

In 设置.py https://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-secure把线

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

并且 cookie 只会通过 HTTPS 连接发送。此外,您可能还想要SESSION_EXPIRE_AT_BROWSER_CLOSE=True。请注意,如果您使用旧版本的 django(低于 1.4),则没有安全 CSRF cookie 的设置。作为一个快速修复,您可以在会话 cookie 安全时让 CSRF cookie 安全(SESSION_COOKIE_SECURE=True),通过编辑django/middleware/csrf.py:

class CsrfViewMiddleware(object):
   ...
   def process_response(self, request, response):
       ...
       response.set_cookie(settings.CSRF_COOKIE_NAME,
            request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52,
            domain=settings.CSRF_COOKIE_DOMAIN,
            secure=settings.SESSION_COOKIE_SECURE or None)

将 HTTP 请求定向到 Web 服务器中的 HTTPS

接下来,您需要一个将 http 请求重定向到 https 的重写规则,例如在 nginx 中

server {
   listen 80;
   rewrite ^(.*) https://$host$1 permanent;
}

姜戈的reversefunction 和 url 模板标签仅返回相对链接;因此,如果您在 https 页面上,您的链接将使您保持在 https 网站上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Django-auth 生成的页面中启用 https? 的相关文章

随机推荐