首先提一個問題:在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=fg2hgasdf
session
在Request Headers中有一個Cookie:cookie="thiscookie"函數
三方網站是沒法獲取cookie計算這個tk簽名的。
2 後臺程序在request中獲取到cookie,也通過time33算法簽名,即token=time33("thiscookie")
。而後與url中帶過來的tk進行比較,若是token==tk
,則認爲是正常的請求。這一步一般是寫在攔截器中的。
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。
django 第一次響應來自某個客戶端的請求時,會在服務器端隨機生成一個 token,把這個 token 放在 客戶端的cookie 裏。
客戶端提交全部的 POST 表單時,必須包含一個 csrfmiddlewaretoken 字段 (只須要在模板里加一個 tag {% csrf_token %}, django 就會自動生成),每次POST請求也會帶上1中的cookie。
服務器端在處理 POST 請求以前,Django 會驗證這個請求cookie 裏的 csrftoken 字段的值和提交的表單裏的 csrfmiddlewaretoken 字段的值是否同樣。若是同樣,則代表這是一個合法的請求。
在全部 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/