Django: Generate new CSRF token per request/form

自古美人都是妖i 提交于 2020-02-26 06:31:28

问题


Can we change CSRF token per-form request or even per-request instead of same token for one active session?


回答1:


In the csrf middleware they do something like this, which overwrites the cookie set:

request.META["CSRF_COOKIE"] = _get_new_csrf_key()

You can import _get_new_csrf_key() via from django.middleware.csrf import _get_new_csrf_key(). Since is kind of a private method I would advise against some hacks like this though.




回答2:


Assuming that you have access to the request object:

from django.middleware.csrf import rotate_token
rotate_token(request)



回答3:


And if you want to use it in a middleware:

from django.middleware.csrf import rotate_token

class CSRFRefresh(object):
    def process_response(self, request, response):
        rotate_token(request)
        return response


来源:https://stackoverflow.com/questions/12615491/django-generate-new-csrf-token-per-request-form

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