简体   繁体   English

Django CSRF cookie HttpOnly

[英]Django CSRF cookie HttpOnly

Is it possible to set the django csrf cookie to be http-only? 是否可以将django csrf cookie设置为仅限http? Alike to SESSION_COOKIE_HTTPONLY with session cookie, but for the csrf one? 与会话cookie一样,对于SESSION_COOKIE_HTTPONLY ,但对于csrf一个?

Django CSRF_COOKIE_HTTPONLY提供了一个新设置CSRF_COOKIE_HTTPONLY

For Django1.6+, check the accepted answer. 对于Django1.6 +,请检查接受的答案。 For Django1.5 and prev, there is not setting option for this. 对于Django1.5和prev,没有为此设置选项。

You could override the process_response() method of django.middleware.csrf.CsrfViewMiddleware and using the customized one instead of CsrfViewMiddleware in MIDDLEWARE_CLASSES 您可以覆盖django.middleware.csrf.CsrfViewMiddlewareprocess_response()方法,并使用MIDDLEWARE_CLASSES的自定义而不是CsrfViewMiddleware

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 或者在CsrfViewMiddleware响应之后调用的另一个中间件

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. 如果你的版本低于1.6,你实际上可以自己修补你的Django文件来模仿更高版本中的功能。

The patch is quite simple, and the files modified are visible here: 补丁非常简单,修改过的文件在这里可见:

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

Pictures showing the edits are provided in case github goes away. 如果github消失,则提供显示编辑的图片。

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. 您无需担心升级会覆盖这些内容,因为升级会包含这些行本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM