Django CSRF cookie HttpOnly

后端 未结 3 697
[愿得一人]
[愿得一人] 2021-02-19 10:50

Is it possible to set the django csrf cookie to be http-only? Alike to SESSION_COOKIE_HTTPONLY with session cookie, but for the csrf one?

3条回答
  •  北海茫月
    2021-02-19 10:57

    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
    

提交回复
热议问题