作用:
是防御CSRF攻击。
如何生成?
在 HTTP 请求中以参数的形式加入一个随机产生的 token,并在服务器端建立一个拦截器来验证这个 token,如果请求中没有 token 或者 token 内容不正确,则认为可能是 CSRF 攻击而拒绝该请求。
应用:
- 表单中:添加隐藏字段csrf_token,来启用csrftoken验证
<form action="/add-name-v2" method="post">
{% csrf_token %}
<input type="text" name="name">
<input type="submit" value="提交">
</form>
不能写到cookie中,因为浏览器在发出恶意csrf请求时,是自动带着你的cookie的。
- Django项目中:
启用csrftoken验证:
from django.template.context_processors import csrf
def login(request):
# omit the detail login logic
return render(request, 'user/login.html', {'form': form, }, csrf(request))
在视图函数当中添加csrf_exempt装饰器,来取消csrftoken验证:
@csrf_exempt
def login(request):
- ajax中的使用: 待补充
参考文档:
https://www.cnblogs.com/mengfangui/p/9075615.html
https://www.ibm.com/developerworks/cn/web/1102_niugang_csrf/#icomments