Django SSL for some pages only

丶灬走出姿态 提交于 2019-12-13 17:11:21

问题


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

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

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

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"

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.).


回答1:


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.

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 and 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)
   return _wrapped_view_func

In your views.py

from decorators import secure_required

@secure_required
def myViewFunction(request):
    ...


来源:https://stackoverflow.com/questions/20742824/django-ssl-for-some-pages-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!