Cross-site request forgery (CSRF) is an attack that tricks a user into making unwanted actions on a website, where they are already authenticated, while they are visiting another site.
- 全局开启csrf防护
# 全局开启csrf防护
django.middleware.csrf.CsrfViewMiddleware # 生成csrf cookie和判断csrf token是否正确
-
针对某一个函数视图开启csrf防护
@csrf_protect def my_view(request): # 函数视图逻辑 return render(request, "example.html")
-
针对某一个类视图开启csrf防护
@method_decorator(csrf_protect) class MyClassView(request): # 类视图逻辑 return render(request, "example.html")
-
在template模版中,使用
{% csrf_token %}
,去生成随机的csrf token(key为csrfmiddlewaretoken的隐藏字段)
注释掉CsrfViewMiddleware中间件,添加csrf_exempt装饰器