23、Django-CSRF跨站伪造请求攻击
配置:
1、在settings.py中确认MIDDLEWARE中 确保
-- django.middleware.csrf.CsrfViewMiddleware 打开
2、在模板中、form标签下添加如下标签:
-- {% csrf_token %} #这个就是页面中的暗号
案例
views.py
---------------------------------------------------------------------------------
#crsf攻击
def test_csrf(request):
if request.method == 'GET':
return render(request, 'test_csrf.html')
elif request.method == 'POST':
print(request.POST)
return HttpResponse('test_csrf in 测试 post')
-----------------------------------------------------------------------------------
test_csrf.html
------------------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>crsf测试</title>
</head>
<body>
<form action="/apicsrf/" method="post">
{% csrf_token %}
<input type="text" name="username">
<input type="submit" name="提交">
</form>
</body>
</html>
-----------------------------------------------------------------------
urls.py
------------------------------------------------------
from django.contrib import admin
from django.urls import path
from midware import views
urlpatterns = [
path('apicsrf/', views.test_csrf)
]
------------------------------------------------------------------------
如果有些视图函数不需要比对csrf的暗号可以局部关掉
#在视图函数中添加装饰器
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
pass