CSRF 概念: CSRF 跨站点请求伪造 (CrossSite Request Forgery), 跟 XSS 攻击一样, 存在巨大的危害性, 你可以这样来理解:
攻击者盗用了你的身份, 以你的名义发送恶意请求, 对服务器来说这个请求是完全合法的, 但是却完成了攻击者所期望的一个操作, 比如以你的名义发送邮件发消息, 盗取你的账号, 添加系统管理员, 甚至于购买商品虚拟货币转账等 如下: 其中 web A 为存在 CSRF 漏洞的网站, Web B 为攻击者构建的恶意网站, User C 为 Web A 网站的合法用户
代码设计
- url(r^csrf1.html/, views.csrf1),
- def csrf1(request):
- if request.method == "GET":
- return render(request,csrf1.html)
- else:
- return HttpResponse(ok)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>csrf1.html</title>
- </head>
- <body>
- <form action="csrf1.html" method="POST">
- {% csrf_token %}# 获取 csrf_token, 并且生成了一个隐藏的 input 标签
- {{ csrf_token }}# 这个是显示 csrf_token, 自己测试看看
- <input type="text"/>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
在 django 里面打开 csrf 机制
通过浏览器访问 http://127.0.0.1:8000/csrf1.html, 如果没有开启这个 csrf 机制, 关闭以后就不会认证开启后, 不获取随机 csrf_token 就会报错
csrf 是随机的一个字符串, 会发给服务端, 然后再次访问的时候带着这个字符串
如果想让某一个函数不验证了, 其他的使用怎么操作?????
要想完成上面的操作, 需要添加一个装饰器, 如下
- 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_exempt,csrf_protect
- # @csrf_exempt
- @csrf_protect# 局部使用
- def csrf1(request):
- if request.method == "GET":
- return render(request,csrf1.html)
- else:
- return HttpResponse(ok)
上面的这些都是 FBV 里面的操作, 下面我们队 CBV 如何操作那
在 django 中的 cbv 里面, 添加装饰器是有不一样的地方的, 它需要把装饰器当成参数传递给另外一个模块中的, 如下面
- from django.views import View
- from django.utils.decorators import method_decorator
- @method_decorator(csrf_protect)
- class Foo(View):
- def get(self,request):
- pass
- def post(self,request):
- pass
django 版本为 1.913 的导入 View 是这样的: from django.views.generic.base import View
也可以通过下面的方式加
还可以指定那个添加
也可以通过 dispatch 来全部加上 (cbv 的原理 dispatch)
注意针对 csrf, 只能添加到类上面,
ajax 发送 csrftoken
第一种方法
ajax 提交数据时候, 携带 csrf 值获取到, 然后通过 data 携带
通过 cookie
需要插件 jquery.cookies.js 插件
$.cooike(csrftocken) 这个是获取, 担任也可以设置
来源: http://www.bubuko.com/infodetail-2507791.html