Joh*_*n C 9 django https django-authentication
使用Django-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>
Run Code Online (Sandbox Code Playgroud)
这很好用,但去了http://mysite.com/login/.
有什么方法可以告诉Django-auth在反转视图名称时使用什么前缀(https)?我已经阅读了整个手册页,但没有找到任何涵盖它的内容.或者也许某种方式告诉url标签转到https?
或者是手动指定整个URL的唯一选项?我希望不是:)鉴于Django到目前为止有多强大,我无法相信它不具备这种能力 - 我必须忽视它.:)
dr *_*bob 11
您需要启用OS环境变量HTTPS,'on'以便django将https添加到完全生成的链接(例如,与HttpRedirectRequests一样).如果您使用的是mod_wsgi,则可以添加以下行:
os.environ['HTTPS'] = "on"
Run Code Online (Sandbox Code Playgroud)
你的wsgi脚本.您可以通过阅读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"
Run Code Online (Sandbox Code Playgroud)
在settings.py中放行
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
Run Code Online (Sandbox Code Playgroud)
和cookie只能通过HTTPS连接发送.此外,您可能也想要SESSION_EXPIRE_AT_BROWSER_CLOSE=True.请注意,如果您使用的是旧版本的django(小于1.4),则没有安全CSRF cookie的设置.作为快速修复,您可以在会话cookie安全(SESSION_COOKIE_SECURE=True)时通过编辑 使CSRF cookie安全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)
Run Code Online (Sandbox Code Playgroud)
接下来,您需要一个重写规则,将http请求重定向到https,例如,在nginx中
server {
listen 80;
rewrite ^(.*) https://$host$1 permanent;
}
Run Code Online (Sandbox Code Playgroud)
Django的reverse函数和url模板标签只返回相对链接; 因此,如果您在https页面上,您的链接将使您保持在https网站上.