為什么80%的碼農都做不了架構師?>>> ??
首先提一個問題:在Django中如何處理CRSF(Cross-site request forgery)?
先看一下CSRF原理。
其實就是惡意網站利用正常網站的cookie去非法請求。
##Java處理方式##
一般做法需要后臺和前端配合采取策略去防止CRSF。
1 前端頁面請求后臺CGI的時候帶上一個參數tk,這個tk是將cookie經過time33算法簽名算得的一個參數。
假設cookie為"thiscookie",tk=time33("thiscookie")=fg2hgasdf;
這樣在CGI上添加tk=fg2hgasdf,當然請求時還會帶上"thiscookie"。所以GET請求可能是這樣的
my.oschina.net/anti-csrf?name=huangyi&tk=fg2hgasdf
在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。
-
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 csrfdef my_view(request):c = {}c.update(csrf(request))# ... view code herereturn 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/