Django使用中间键实现csrf认证详解
Django中的csrf认证实现的原理
调用process_view方法
检查视图是否被@csrf_exempt(免除csrf认证)
-去请求体或cookie中获取token
情况一(全站使用csrf认证,局部不想使用csrf认证)
MIDDLEWARE=[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',#全站使用csrf认证 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
如果我想让某个请求不通过csrf认证可以这样做
fromdjango.views.decorators.csrfimportcsrf_exempt @csrf_exempt#该函数无需认证 defusers(request): user_list=['alex','oldboy'] returnHttpResponse(json.dumps((user_list)))
情况二(全站不使用csrf认证,局部想使用csrf认证)
MIDDLEWARE=[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware',#全站不使用csrf认证 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
如果我想让某个请求使用csrf认证可以这样做
fromdjango.views.decorators.csrfimportcsrf_exempt,csrf_protect @csrf_protect#该函数需认证 defusers(request): user_list=['alex','oldboy'] returnHttpResponse(json.dumps((user_list)))
CBV小知识,csrf时需要使用
-@method_decorator(csrf_exempt)
-在dispatch方法中(单独方法无效)
方式一
fromdjango.views.decorators.csrfimportcsrf_exempt,csrf_protect fromdjango.utils.decoratorsimportmethod_decorator classStudentsView(View): @method_decorator(csrf_exempt) defdispatch(self,request,*args,**kwargs): returnsuper(StudentsView,self).dispatch(request,*args,**kwargs) defget(self,request,*args,**kwargs): print('get方法') returnHttpResponse('GET') defpost(self,request,*args,**kwargs): returnHttpResponse('POST') defput(self,request,*args,**kwargs): returnHttpResponse('PUT') defdelete(self,request,*args,**kwargs): returnHttpResponse('DELETE')
方式二
fromdjango.views.decorators.csrfimportcsrf_exempt,csrf_protect fromdjango.utils.decoratorsimportmethod_decorator @method_decorator(csrf_exempt,name='dispatch') classStudentsView(View): defget(self,request,*args,**kwargs): print('get方法') returnHttpResponse('GET') defpost(self,request,*args,**kwargs): returnHttpResponse('POST') defput(self,request,*args,**kwargs): returnHttpResponse('PUT') defdelete(self,request,*args,**kwargs): returnHttpResponse('DELETE')
总结:
- -本质,基于反射来实现
- -流程:路由,view,dispatch(反射)
- -取消csrf认证(装饰器要加到dispatch方法上且method_decorator装饰)
扩展:
- -csrf
- -基于中间件的process_view方法
- -装饰器给单独函数进行设置(认证或无需认证)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。