django如何設(shè)置csrf_token
一、關(guān)于csrf_token
- csrf:跨站請求偽造,防止其他人改造,盜取信息,反正就是一種網(wǎng)站的防護(hù)措施
- 服務(wù)器端:設(shè)置隨機的csrf_token,get請求的時候就該設(shè)置好
- 客戶端:攜帶上相應(yīng)的csrf_token,post請求的時候攜帶上
二、form表單設(shè)置csrf_token
通過模板標(biāo)簽進(jìn)行設(shè)置

當(dāng)提交post請求的時候會自動帶上
三、針對某個類視圖設(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針對整個項目中所有視圖設(shè)置csrf_token
①自定義中間件,在utils目錄下創(chuàng)建CsrfMiddleware.py,如下圖所示:

②注冊中間件,在項目目錄下的settings.py中,如圖所示寫上全路徑

四、提交post請求攜帶csrf_token
前面說到,form表單是自動攜帶上的,那么ajax請求是如何攜帶csrf_token的呢?
很簡單,通過jquery獲取,在ajax請求之后附加如下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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pytorch之pytorch?hook和關(guān)于pytorch?backward過程問題
這篇文章主要介紹了pytorch之pytorch?hook和關(guān)于pytorch?backward過程問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Python sklearn庫實現(xiàn)PCA教程(以鳶尾花分類為例)
今天小編就為大家分享一篇Python sklearn庫實現(xiàn)PCA教程(以鳶尾花分類為例),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python爬蟲數(shù)據(jù)處理模塊的安裝使用教程
這篇文章主要為大家介紹了Python爬蟲數(shù)據(jù)處理模塊的安裝使用教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
win8.1安裝Python 2.7版環(huán)境圖文詳解
在本篇內(nèi)容里小編給大家分享了關(guān)于win8.1安裝Python 2.7版環(huán)境的詳細(xì)步驟和方法,有興趣的朋友們跟著學(xué)習(xí)下。2019-07-07
利用ImageAI庫只需幾行python代碼實現(xiàn)目標(biāo)檢測
這篇文章主要介紹了利用ImageAI庫只需幾行python代碼超簡實現(xiàn)目標(biāo)檢測功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08

