一弯拱桥对映着一弯晓月,桥下流水波光粼粼,昙花一般的月,在我眼中异香腾风,秀色媚景。夜的静谧是风景,昼的明媚是风景。江花胜火红,寒山伤心碧,空伫玉阶白,西风残照黄。处处皆风景,处处皆绝妙风景。
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认证详解到此结束。曾以为我是那崖畔的一枝花,后来才知道,不过是人海一粒渣。小编再次感谢大家对我们的支持!