当前位置:主页 > 软件编程 > Python代码 >

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

时间:2020-11-29 10:58:56 | 栏目:Python代码 | 点击:

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')

总结:

扩展:

您可能感兴趣的文章:

相关文章