基本应用
def csrf1(request): if request.method == 'GET': return render(request,'csrf1.html') else: return HttpResponse('ok')
三种传递csrf的方法,一表单提交,二ajax提交,三ajax提交隐藏的csrf input标签中的值
CSRF:POST时,需要用户携带服务端发送过来的随机字符,然后在服务端进行验证,csrf也具有时效性。 a.表单提交,携带CSRF: <form method="POST" action="/csrf1.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type="submit" value="提交"/> </form> Ajax提交数据时候,携带CSRF: b. 放置在data中携带 <form method="POST" action="/csrf1.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form> <script src="/static/jquery-1.12.4.js"></script> <script> function submitForm(){ var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url: '/csrf1.html', type: 'POST', data: { "user":user,'csrfmiddlewaretoken': csrf}, success:function(arg){ console.log(arg); } }) } </script> c. 放在请求头中 console.log(document.cookie) 查询csrftoken字符串 csrf_token中的随机字符串和cookie中的csrftoken值不一样 <form method="POST" action="/csrf1.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form> <script src="/static/jquery-1.12.4.js"></script> <script src="/static/jquery.cookie.js"></script> #导入去取cookie中的csrftoken得文件 <script> function submitForm(){ var token = $.cookie('csrftoken'); #取cookie中的csrftoken var user = $('#user').val(); $.ajax({ url: '/csrf1.html', type: 'POST', headers:{'X-CSRFToken': token}, data: { "user":user}, success:function(arg){ console.log(arg); } }) } </script>
csrf禁用
b. 全站禁用 # 'django.middleware.csrf.CsrfViewMiddleware', c. 局部禁用 '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') d. 局部使用 # 'django.middleware.csrf.CsrfViewMiddleware', 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')
添加csrf装饰器:
c. 特殊CBV(cxrf装饰器只能加在类上,这是一个bug)
from django.views import View
from django.utils.decorators import method_decorator
@method_decorator(csrf_protect,name='dispatch')
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
PS:CBV中添加装饰器
def wrapper(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
# 1. 指定方法上添加装饰器
# class Foo(View):
#
# @method_decorator(wrapper)
# def get(self,request):
# pass
#
# def post(self,request):
# pass
# 2. 在类上添加
# @method_decorator(wrapper,name='dispatch')
或者@method_decorator(wrapper,name='get') 只给一个方法加
# class Foo(View):
#
# def get(self,request):
# pass
#
# def post(self,request):
# pass