Django学习笔记(4)

首先提一个问题:在Django中如何处理CRSF(Cross-site request forgery)?html

先看一下CSRF原理。前端

输入图片说明

其实就是恶意网站利用正常网站的cookie去非法请求。web

##Java处理方式##ajax

通常作法须要后台和前端配合采起策略去防止CRSF。算法

1 前端页面请求后台CGI的时候带上一个参数tk,这个tk是将cookie通过time33算法签名算得的一个参数。django

假设cookie为"thiscookie",tk=time33("thiscookie")=fg2hgasdf;服务器

这样在CGI上添加tk=fg2hgasdf,固然请求时还会带上"thiscookie"。因此GET请求多是这样的cookie

my.oschina.net/anti-csrf?name=huangyi&tk=fg2hgasdfsession

在Request Headers中有一个Cookie:cookie="thiscookie"函数

三方网站是没法获取cookie计算这个tk签名的。

2 后台程序在request中获取到cookie,也通过time33算法签名,即token=time33("thiscookie") 。而后与url中带过来的tk进行比较,若是token==tk,则认为是正常的请求。这一步一般是写在拦截器中的。

Django解决方法

Django自带CRSF的解决方法

Thankfully, you don’t have to worry too hard, because Django comes with a very easy-to-use system for protecting against it. In short, all POST forms that are targeted at internal URLs should use the {% csrf_token %} template tag。

  1. django 第一次响应来自某个客户端的请求时,会在服务器端随机生成一个 token,把这个 token 放在 客户端的cookie 里。

  2. 客户端提交全部的 POST 表单时,必须包含一个 csrfmiddlewaretoken 字段 (只须要在模板里加一个 tag {% csrf_token %}, django 就会自动生成),每次POST请求也会带上1中的cookie。

  3. 服务器端在处理 POST 请求以前,Django 会验证这个请求cookie 里的 csrftoken 字段的值和提交的表单里的 csrfmiddlewaretoken 字段的值是否同样。若是同样,则代表这是一个合法的请求。

  4. 在全部 ajax POST 请求里,添加一个 X-CSRFTOKEN header,其值为 cookie 里的 csrftoken 的值

前端页面

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="submit to Vote" />
</form>

只须要在表单中加入{% csrf_token %}便可,做用是生成表单的csrfmiddlewaretoken字段。

输入图片说明

在请求的头中能够看见Cookie有两个元素

Cookie:sessionid=fg2xeknnq2f37a0yvz9rpmmmu78lk4vi; 
csrftoken=aFuwdo1WRnnwN9KlWK4oVZF1PO6DtDFG

表单FormData中含有一个 csrfmiddlewaretoken 字段。

后台服务主要是验证cookie中的csrftoken与csrfmiddlewaretoken字段是否相等,在CsrfViewMiddleware中实现。

同时对应{% csrf_token %}模板写法,须要在views函数中加入

from django.shortcuts import render_to_response
from django.template.context_processors import csrf

def my_view(request):
    c = {}
    c.update(csrf(request))
    # ... view code here
    return render_to_response("a_template.html", c)

##参考

https://www.ibm.com/developerworks/cn/web/1102_niugang_csrf/

https://docs.djangoproject.com/en/1.8/ref/csrf/

相关文章
相关标签/搜索