python

超轻量级php框架startmvc

Django使用中间键实现csrf认证详解

更新时间:2020-07-17 04:48:01 作者:startmvc
Django中的csrf认证实现的原理调用process_view方法检查视图是否被@csrf_exempt(免除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认证可以这样做


from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # 该函数无需认证
def users(request):
 user_list = ['alex','oldboy']
 return HttpResponse(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认证可以这样做


from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect # 该函数需认证
def users(request):
 user_list = ['alex','oldboy']
 return HttpResponse(json.dumps((user_list)))

CBV小知识,csrf时需要使用

- @method_decorator(csrf_exempt)

- 在dispatch方法中(单独方法无效)

方式一


from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
class StudentsView(View):
 
 @method_decorator(csrf_exempt)
 def dispatch(self, request, *args, **kwargs):
 return super(StudentsView,self).dispatch(request, *args, **kwargs)

 def get(self,request,*args,**kwargs):
 print('get方法')
 return HttpResponse('GET')

 def post(self, request, *args, **kwargs):
 return HttpResponse('POST')

 def put(self, request, *args, **kwargs):
 return HttpResponse('PUT')

 def delete(self, request, *args, **kwargs):
 return HttpResponse('DELETE')

方式二


from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt,name='dispatch')
class StudentsView(View):

 def get(self,request,*args,**kwargs):
 print('get方法')
 return HttpResponse('GET')

 def post(self, request, *args, **kwargs):
 return HttpResponse('POST')

 def put(self, request, *args, **kwargs):
 return HttpResponse('PUT')

 def delete(self, request, *args, **kwargs):
 return HttpResponse('DELETE')

总结:

  • - 本质,基于反射来实现
  • - 流程:路由,view,dispatch(反射)
  • - 取消csrf认证(装饰器要加到dispatch方法上且method_decorator装饰)

扩展:

  • - csrf
    • - 基于中间件的process_view方法
    • - 装饰器给单独函数进行设置(认证或无需认证)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

django 中间键 csrf认证