drf 取消csrf token校验
2021-06-13 本文已影响0人
clever哲思
背景
因为csrftoken的校验一般是后端放在html模板中, 然后前端在提交form表单时一起提交给后端做校验, 但是在前后端分离的项目中, 都是通过ajax请求来完成的, 所以想取消这个校验
但是Django框架是默认开启这个校验的, 并且关闭后无法使用.
代码
先上代码, 再说原理
class CustomMiddleware(MiddlewareMixin):
def process_request(self, request):
setattr(request, "_dont_enforce_csrf_checks", True)
在中间件中, 给每一个request, 赋值_dont_enforce_csrf_checks
为True
源码剖析
在django/middleware/csrf.py的CsrfViewMiddleware中有这样一个方法,
def process_view(self, request, callback, callback_args, callback_kwargs):
if getattr(request, 'csrf_processing_done', False):
return None
# Wait until request.META["CSRF_COOKIE"] has been manipulated before
# bailing out, so that get_token still works
if getattr(callback, 'csrf_exempt', False):
return None
# Assume that anything not defined as 'safe' by RFC7231 needs protection
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
if getattr(request, '_dont_enforce_csrf_checks', False): # 这个是重点, 修改的就是这个参数, 来达到目的
# Mechanism to turn off CSRF checks for test suite.
# It comes after the creation of CSRF cookies, so that
# everything else continues to work exactly the same
# (e.g. cookies are sent, etc.), but before any
# branches that call reject().
return self._accept(request)