Django csrf校验的实现
作者:Hank·Paul 时间:2023-10-01 14:49:40
引入:
通常,钓鱼网站本质是本质搭建一个跟正常网站一模一样的页面,用户在该页面上完成转账功能
转账的请求确实是朝着正常网站的服务端提交,唯一不同的在于收款账户人不同。
如果想模拟一个钓鱼网站,就可是给用户书写一个form表单 对方账户的input框没有name属性,然后你自己悄悄提前写好了一个具有默认的并且是隐藏的具有name属性的input框。
如果想解决这个问题,当转账请求发送给服务端后,服务端会给各台机器返回一个随机实时字符串。下一次,如果还有请求向服务端发时,服务端会校验字符串,若对不上的话服务端就拒绝访问。这就是csrf校验。
那么form表单如何进行csrf校验呢?
你只需要在你的form表单内写一个{% csrf_token %}就可以了
Ajax请求设置csrf_token的三种方式
示例:
urls.py
urlpatterns = [
url(r'^transfer/', views.transfer),
]
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
第三种方式的js文件(官方文档套用就行了)
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
views.py
def transfer(request):
if request.method =='POST':
username = request.POST.get('username')
target_user = request.POST.get('target_user')
money = request.POST.get('money')
print('%s 给 %s 转账 %s元' %(username,target_user,money))
return render(request,'transfer.html')
前端页面 transfer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
<p>username:<input type="text" name="username"></p>
<p>target_user:<input type="text" name="target_user"></p>
<p>money:<input type="text" name="money"></p>
<input type="submit">
</form>
<button id="d1">发送ajax请求</button>
{% load static %}
<script src="{% static 'myfile.js' %}"></script>
<script>
$('#d1').click(function () {
$.ajax({
url:'',
type:'post',
// 第一种方式 自己手动获取
{#data:{'username':'jason','csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},#}
// 第二种方式 利用模板语法
{#data:{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},#}
// 第三种 通用方式 引入外部js文件
data:{'username':'hank'},
success:function (data) {
alert(data)
}
})
})
</script>
</body>
</html>
csrf装饰器
csrf装饰器作用在FBV上
装饰器模块导入:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
当我们网站整体都校验csrf的时候 我想让某几个视图函数不校验
@csrf_exempt #给哪个视图函数加上,就不给哪个视图校验csrf
当我们网站整体都不校验csrf的时候 我想让某几个视图函数校验
@csrf_protect #给哪个视图函数加上,就给哪个视图校验csrf
注意:验证同时需要把'django.middleware.csrf.CsrfViewMiddleware'注销掉
csrf装饰器作用在CBV上
当我们网站整体都不校验csrf的时候 我想让某几个视图函数校验
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt,csrf_protect
# @method_decorator(csrf_protect,name='post') #第二种指名道姓地给某给方法装
class MyHome(View):
@method_decorator(csrf_protect) #第三种 给类中所有的方法都装
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
def get(self,request):
return HttpResponse('get')
# @method_decorator(csrf_protect) #第一种方式
def post(self,request):
return HttpResponse('post')
注意:验证同时需要把'django.middleware.csrf.CsrfViewMiddleware'注销掉
当我们网站整体都校验csrf的时候 我想让某几个视图函数不校验
总结:给CBV加装饰器 推荐使用模块method_decorator
csrf_exempt 只能给dispatch方法装
来源:https://www.cnblogs.com/baohanblog/p/12193711.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Tensorflow tf.nn.atrous_conv2d如何实现空洞卷积的
![](https://img.aspxhome.com/file/2023/4/126894_0s.png)
修改数据库为多用户模式
laravel学习教程之关联模型
Python信息抽取之乱码解决办法
教你用PyTorch部署模型的方法
![](https://img.aspxhome.com/file/2023/1/113131_0s.jpg)
Python实现栈的方法详解【基于数组和单链表两种方法】
![](https://img.aspxhome.com/file/2023/1/114771_0s.png)
Python3.4编程实现简单抓取爬虫功能示例
浅谈SQL Server中统计对于查询的影响分析
![](https://img.aspxhome.com/file/2023/8/124848_0s.png)
js遍历详解(forEach, map, for, for...in, for...of)
JavaScript数据结构中串的表示与应用实例
详解MySQL中的事务与ACID特性
MySQL与SQLserver的差异对比
Python搜索引擎实现原理和方法
![](https://img.aspxhome.com/file/2023/7/67327_0s.png)
解决Python字典查找报Keyerror的问题
![](https://img.aspxhome.com/file/2023/0/100800_0s.png)
Python实现PS滤镜的万花筒效果示例
![](https://img.aspxhome.com/file/2023/9/134539_0s.jpg)
Django自定义用户认证示例详解
![](https://img.aspxhome.com/file/2023/5/134495_0s.png)
对于Python装饰器使用的一些建议
MySQL 查询缓存的实际应用代码示例
Spark GraphX 分布式图处理框架图算法详解
![](https://img.aspxhome.com/file/2023/7/132467_0s.png)