Django CSRF cookie HttpOnly

江枫思渺然 提交于 2019-11-30 18:28:50

A new setting, CSRF_COOKIE_HTTPONLY, is available in Django 1.6+.

For Django1.6+, check the accepted answer. For Django1.5 and prev, there is not setting option for this.

You could override the process_response() method of django.middleware.csrf.CsrfViewMiddleware and using the customized one instead of CsrfViewMiddleware in MIDDLEWARE_CLASSES

class Foo(CsrfViewMiddleware):
    def process_response(self, request, response):
        response = super(Foo, self).process_response(request, response)
        response.cookies[settings.CSRF_COOKIE_NAME]['httponly'] = True
        return response

Or in another middleware which is invoked after CsrfViewMiddleware in response

class Foo(object):
    def process_response(self, request, response):
        if settings.CSRF_COOKIE_NAME in response.cookies:
            response.cookies[settings.CSRF_COOKIE_NAME]['httponly'] = True
        return response

You could actually patch your Django files themselves to mimic the functionality present in later versions, if you have below version 1.6.

The patch is quite simple, and the files modified are visible here:

https://github.com/django/django/commit/720888a14699a80a6cd07d32514b9dcd5b1005fb

Pictures showing the edits are provided in case github goes away.

Here's the rest of that page.

You don't need to worry about these being overwritten by an upgrade, since the upgrade would include these lines itself.

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