Django - 使用 {% url %} 生成的链接 - 如何确保它们安全?
如果我想为用户提供使用 https://
而不是 http://
登录网站的选项,我最好给他们一个选项在我的视图或模板中到达那里。
我希望在我的登录页面上有“使用安全连接”链接 - 但是,如何在不硬编码 URL 的情况下做到这一点呢?
我希望能够这样做:
{% url login_page %}
{% url login_page_https %}
并让它们指向 http://example.com/login
和 https://example.com/login
。
我该怎么做?
If I want to give an option for users to log in to a website using https://
instead of http://
, I'd best to give them an option to get there in my view or template.
I'd like to have the link "Use secure connection" on my login page - but then, how do I do it without hardcoding the URL?
I'd like to be able to just do:
{% url login_page %}
{% url login_page_https %}
and have them point to http://example.com/login
and https://example.com/login
.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
{% url %}
标记仅生成 URL 的路径部分,而不是主机部分。它只会生成类似“/path/to/here”的内容(您所需要做的就是“查看源代码”,您将看到这是href
的全部内容)。您的浏览器会假设您当前位于 http://example.com 上,则链接也应位于 http://example.com。因此,在模板中生成安全链接所需要做的就是:如果您不想对域名进行硬编码(我也不会),则可以使用 Site 对象 并使其看起来像这样:
或者如果您不想使用站点框架,您可以使用 request.get_host :
The
{% url %}
tag only generates the path portion of the URL, not the host portion. It only generates something like "/path/to/here" (all you need to do is "view source" and you'll see that's the entire contents of thehref
). It's your browser that assumes if you're currently on http://example.com the link should also be within http://example.com. So all you need to do to generate a secure link in your template is:If you don't want to hardcode the domain name (and I wouldn't), you can use the Site object and have it look something like:
Or if you don't want to use the sites framework, you can use
request.get_host
:我对安全 URL 的研究不多,但我对 satchmo 进行了一些研究,它有一个中间件和一些实用程序。中间件仅检查视图参数中的密钥
SSL = True
,并以这种方式确保请求的安全。你可能不需要把它弄得那么复杂,但你可以看看它是如何实现的。Satchmo 位于 bitbucked 此处
我还能够找到中间件的片段,这也应该是能够帮助您获得安全的登录网址:
第一个是原始版本,而第二个应该是改进版本,在某些时候,但可能不再是这样了。你可以看看它们。
使用 satchmo 或中间件片段之一,您应该能够执行类似的操作
I've not worked much with secure urls, but I have worked a bit with satchmo, which has a middleware and some utils for it. The middleware just checks for the key
SSL = True
in the view parameters, and makes the request secure that way. You probably don't need to make it that complex, but you can take a look at how it's implemented.Satchmo is on bitbucked here
I was also able to find a snippets for middlewares which also should be able to help you get a secure login url:
The first is the original, while the 2nd should be ab improved version, at some point, but might not be the case anymore. You can take a look into them.
Using either satchmo or one of the middleware snippets you should be able to do something like
也许您可以编写一个标签
url_https
,其功能与url
相同,但指向 URL 的 HTTPS 版本。Perhaps you could write a tag
url_https
that does the same thing asurl
but points to the HTTPS version of the url.