CSRF补充--跨站请求伪造FBV

FBV              

应用一:在form表单中,添加随机csrf字符串

<body>
    <form method="post" action="csrf1.html"></form>
        {% csrf_token %}
        <input type="text" name="user"/>
        <input type="submit" value="提交"/>
</body>
csrf1
<input type='hidden' name='csrfmiddlewaretoken' value='EZ5ww0bjRs9YysjESYJh5Jz2OO4XRZj2YICEv6Dppj0OzQNAiU3qqF9EezuqO1gl' />
源码出现
def csrf1(request):
    if request.method =='GET':
        return render(request,'csrf1.html')
    else:
        return HttpResponse('ok')
Views
'django.middleware.csrf.CsrfViewMiddleware',
settings
{% csrf_token %} 

##不只在表单生成隐藏的input框,提交的时候带过去
##还在本地的cookie中,也会加上随机字符串。

应用二:全站禁用。注释掉csrf。

'django.middleware.csrf.CsrfViewMiddleware',

应用三,局部禁用
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def csrf1(request):
    if request.method =='GET':
        return render(request,'csrf1.html')
    else:
        return HttpResponse('ok')

#局部禁用,单独在某个函数上,添加装饰器
#全站使用的前提下,才会出现局部禁用

应用四:局部使用

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def csrf1(request):
if request.method =='GET':
return render(request,'csrf1.html')
else:
return HttpResponse('ok')

CBV            

from django.views import view
from django.utils.decorators import method_decorator 

def wrapper(func)
     def inner(*args,**kwargs):
           return func(*args,**kwargs)
      return inner

@method_decorator(wrapper,name='get')
@method_decorator(wrapper,name='post')

@method_decorator(wrapper,name='dispatch')  #给所有的都加上了
class Foo(view)
     def dispatch(self,request,*args,**kwargs):
           return xxx

    #@method_decorator(wrapper)
    def get(self,request):
     pass

     # @method_decorator(wrapper)
     def post(self,request):
     pass

### django CBV内不允许直接添@csrf
### CBV应用装饰器,必须用method_decorator    


###@method_decorator(wrapper,name='dispatch')  
##请求来了,先都到dispatch中,dispatch通过反射执行get/post。

1,指定方法上,添加装饰器。

    不用添加name='dispatch'

@method_decorator(wrapper)
from django.views import view
from django.utils.decorators import method_decorator 

1,指定方法上添加装饰器

class Foo(view)
     
    @method_decorator(wrapper)
    def get(self,request):
     pass

     def post(self,request):
     pass

2,在类上面添加,需要指定name

from django.views import view
from django.utils.decorators import method_decorator 

2,指定类上添加

@method_decorator(csrf_protect,name='dispatch')
class Foo(view)
     
    def get(self,request):
     pass

     def post(self,request):
     pass

猜你喜欢

转载自www.cnblogs.com/catherine007/p/8929596.html