Django SSL仅适用于某些页面 [英] Django SSL for some pages only

查看:154
本文介绍了Django SSL仅适用于某些页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有其他Q / A,但它们太低级了。

I know there are other Q/A about that but they are too low-level.

我想知道什么是正确的(安全,干,可维护) )在django网站上实现部分SSL的方式。

I want to know what is the proper (secure, DRY, maintainable) way of implementing partial SSL on a django site.

我想在帐户页面上使用https(登录,单身,......)和应用页面,但是将公共内容页面保存在http中。

I would like to have https on account pages (login, singup, ...) and "applicative pages", but keep public content pages in http.

我对各种答案持开放态度,但请解释如无处不在使用https,它有专业X,Y ,Z超过缺点A,B,C你必须使用2个饼干

I am open to every kind of answers, but please explain like "use https everywhere, it has pros X, Y, Z that exceed cons A, B, C", or "you have to use 2 cookies"

如果不是做我说的坏主意,我特别想知道如何处理非安全页面上的安全cookie(知道我希望通过我的网站保持一致的体验,让用户登录等) 。

If it's not a bad idea to do what I say, I'd especially like to know what to do with secure cookies on non-secure pages (knowing that I want to keep a consistent experience through my site, keeping users logged-in, etc.).

推荐答案

每当您需要一些需要在某些选定视图上应用的功能时,就可以使用装饰器了。另一方面,如果你想实现应该应用于所有请求的东西,那么我们应该使用中间件。

Whenever you need a functionality which needs to be applied on some selected views, then using decorators is the way to go. On the other hand if you want to implement something which should be applied on all requests, then we should use a middleware.

创建一个装饰器,它将传入的请求重定向到https。

Create a decorator which will redirect the incoming request to https.

#decorators.py
from django.http import HttpResponseRedirect

def secure_required(view_func):
    def _wrapped_view_func(request, *args, **kwargs):
        if request:
            if not request.is_secure():
                request_url = request.build_absolute_uri(request.get_full_path())
                secure_url = request_url.replace('http://', 'https://')
                return HttpResponseRedirect(secure_url)
            return view_func(request, *args, **kwargs)
        else:
            return view_func(request, *args, **kwargs)
   return _wrapped_view_func

在你的views.py

In your views.py

from decorators import secure_required

@secure_required
def myViewFunction(request):
    ...

这篇关于Django SSL仅适用于某些页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆