Cross Site Request Forgery protection for Django
为了安全Django在1.4之后的版本中都开启了CSRF功能,通过以下配置开启并使用。
- 1)在settings.py中的MIDDLEWARE_CLASSES中加入
django.middleware.csrf.CsrfViewMiddleware - 2)在模版文件中针对POST方法的form中加入{% csrf_token %},它将生成一个隐藏控件用于提交token进行验证;
<form method="post">
{% csrf_token %}
</form>
如果使用了Ajax可以通过Cookie中获取token并将token通过HTTP头发送给服务器。
// using 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 = 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;
}
"X-CSRFToken":getCookie('csrftoken')
