django如何設(shè)置csrf_token
一、關(guān)于csrf_token
- csrf:跨站請(qǐng)求偽造,防止其他人改造,盜取信息,反正就是一種網(wǎng)站的防護(hù)措施
- 服務(wù)器端:設(shè)置隨機(jī)的csrf_token,get請(qǐng)求的時(shí)候就該設(shè)置好
- 客戶端:攜帶上相應(yīng)的csrf_token,post請(qǐng)求的時(shí)候攜帶上
二、form表單設(shè)置csrf_token
通過(guò)模板標(biāo)簽進(jìn)行設(shè)置
當(dāng)提交post請(qǐng)求的時(shí)候會(huì)自動(dòng)帶上
三、針對(duì)某個(gè)類(lèi)視圖設(shè)置csrf_token
from django.views.decorators.csrf import ensure_csrf_cookie from django.utils.decorators import method_decorator from django.views import View class LoginView(View): @method_decorator(ensure_csrf_cookie) def get(self, request): pass def post(self, request): pass
針對(duì)整個(gè)項(xiàng)目中所有視圖設(shè)置csrf_token
①自定義中間件,在utils目錄下創(chuàng)建CsrfMiddleware.py,如下圖所示:
②注冊(cè)中間件,在項(xiàng)目目錄下的settings.py中,如圖所示寫(xiě)上全路徑
四、提交post請(qǐng)求攜帶csrf_token
前面說(shuō)到,form表單是自動(dòng)攜帶上的,那么ajax請(qǐng)求是如何攜帶csrf_token的呢?
很簡(jiǎn)單,通過(guò)jquery獲取,在ajax請(qǐng)求之后附加如下js代碼:
// get cookie using jQuery function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(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; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } // Setting the token on the AJAX request $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } });
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python的dataframe轉(zhuǎn)換為多維矩陣的方法
下面小編就為大家分享一篇python的dataframe轉(zhuǎn)換為多維矩陣的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04python對(duì)list中的每個(gè)元素進(jìn)行某種操作的方法
今天小編就為大家分享一篇python對(duì)list中的每個(gè)元素進(jìn)行某種操作的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06使用Python實(shí)現(xiàn)在Word文檔中進(jìn)行郵件合并
郵件合并是現(xiàn)代辦公中一項(xiàng)顯著提升效率的技術(shù),它巧妙地將大量個(gè)體數(shù)據(jù)與預(yù)設(shè)的文檔模板相結(jié)合,實(shí)現(xiàn)了一次性批量生成定制化文檔,下面我們就來(lái)看看如何使用Python實(shí)現(xiàn)在Word文檔中進(jìn)行郵件合并吧2024-04-04Python中Timedelta轉(zhuǎn)換為Int或Float方式
這篇文章主要介紹了Python中Timedelta轉(zhuǎn)換為Int或Float方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07使用Python腳本和ADB命令實(shí)現(xiàn)卸載App
這篇文章主要介紹了使用Python腳本和ADB命令實(shí)現(xiàn)卸載App的實(shí)現(xiàn)方法,文中給出了完整的示例代碼,相信對(duì)大家具有一定的參考價(jià)值,有需要的朋友們下面來(lái)一起看看吧。2017-02-02