Django csrf校驗的實現(xiàn)
引入:
通常,釣魚網(wǎng)站本質(zhì)是本質(zhì)搭建一個跟正常網(wǎng)站一模一樣的頁面,用戶在該頁面上完成轉(zhuǎn)賬功能
轉(zhuǎn)賬的請求確實是朝著正常網(wǎng)站的服務(wù)端提交,唯一不同的在于收款賬戶人不同。
如果想模擬一個釣魚網(wǎng)站,就可是給用戶書寫一個form表單 對方賬戶的input框沒有name屬性,然后你自己悄悄提前寫好了一個具有默認(rèn)的并且是隱藏的具有name屬性的input框。
如果想解決這個問題,當(dāng)轉(zhuǎn)賬請求發(fā)送給服務(wù)端后,服務(wù)端會給各臺機(jī)器返回一個隨機(jī)實時字符串。下一次,如果還有請求向服務(wù)端發(fā)時,服務(wù)端會校驗字符串,若對不上的話服務(wù)端就拒絕訪問。這就是csrf校驗。
那么form表單如何進(jìn)行csrf校驗?zāi)兀?/p>
你只需要在你的form表單內(nèi)寫一個{% csrf_token %}就可以了
Ajax請求設(shè)置csrf_token的三種方式
示例:
urls.py
urlpatterns = [ url(r'^transfer/', views.transfer), ]
settings.py
STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
第三種方式的js文件(官方文檔套用就行了)
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var 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; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
views.py
def transfer(request): if request.method =='POST': username = request.POST.get('username') target_user = request.POST.get('target_user') money = request.POST.get('money') print('%s 給 %s 轉(zhuǎn)賬 %s元' %(username,target_user,money)) return render(request,'transfer.html')
前端頁面 transfer.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="external nofollow" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <form action="" method="post"> {% csrf_token %} <p>username:<input type="text" name="username"></p> <p>target_user:<input type="text" name="target_user"></p> <p>money:<input type="text" name="money"></p> <input type="submit"> </form> <button id="d1">發(fā)送ajax請求</button> {% load static %} <script src="{% static 'myfile.js' %}"></script> <script> $('#d1').click(function () { $.ajax({ url:'', type:'post', // 第一種方式 自己手動獲取 {#data:{'username':'jason','csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},#} // 第二種方式 利用模板語法 {#data:{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},#} // 第三種 通用方式 引入外部js文件 data:{'username':'hank'}, success:function (data) { alert(data) } }) }) </script> </body> </html>
csrf裝飾器
csrf裝飾器作用在FBV上
裝飾器模塊導(dǎo)入:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
當(dāng)我們網(wǎng)站整體都校驗csrf的時候 我想讓某幾個視圖函數(shù)不校驗
@csrf_exempt #給哪個視圖函數(shù)加上,就不給哪個視圖校驗csrf
當(dāng)我們網(wǎng)站整體都不校驗csrf的時候 我想讓某幾個視圖函數(shù)校驗
@csrf_protect #給哪個視圖函數(shù)加上,就給哪個視圖校驗csrf
注意:驗證同時需要把'django.middleware.csrf.CsrfViewMiddleware'注銷掉
csrf裝飾器作用在CBV上
當(dāng)我們網(wǎng)站整體都不校驗csrf的時候 我想讓某幾個視圖函數(shù)校驗
from django.views import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt,csrf_protect # @method_decorator(csrf_protect,name='post') #第二種指名道姓地給某給方法裝 class MyHome(View): @method_decorator(csrf_protect) #第三種 給類中所有的方法都裝 def dispatch(self, request, *args, **kwargs): return super().dispatch(request,*args,**kwargs) def get(self,request): return HttpResponse('get') # @method_decorator(csrf_protect) #第一種方式 def post(self,request): return HttpResponse('post')
注意:驗證同時需要把'django.middleware.csrf.CsrfViewMiddleware'注銷掉
當(dāng)我們網(wǎng)站整體都校驗csrf的時候 我想讓某幾個視圖函數(shù)不校驗
總結(jié):給CBV加裝飾器 推薦使用模塊method_decorator
csrf_exempt 只能給dispatch方法裝
到此這篇關(guān)于Django csrf校驗的實現(xiàn)的文章就介紹到這了,更多相關(guān)Django csrf校驗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對Pycharm創(chuàng)建py文件時自定義頭部模板的方法詳解
今天小編就為大家分享一篇對Pycharm創(chuàng)建py文件時自定義頭部模板的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python?dateutil庫簡化日期時間處理利器使用場景實踐
在Python中,處理日期和時間是常見的任務(wù)之一,dateutil庫是Python標(biāo)準(zhǔn)庫中datetime模塊的擴(kuò)展,提供了許多方便的工具和函數(shù),簡化了日期和時間的操作2023-12-12Python小程序 控制鼠標(biāo)循環(huán)點擊代碼實例
這篇文章主要介紹了Python小程序 控制鼠標(biāo)循環(huán)點擊代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10Python web開發(fā)之用Tornado框架制作簡易表白墻網(wǎng)站
這篇文章將用Python做Web開發(fā)。在Python當(dāng)中,WEB開發(fā)框架主要有三個,本文將利用Tornado框架做一個簡單的表白墻網(wǎng)站,感興趣的可以了解一下2022-02-02python開發(fā)之tkinter實現(xiàn)圖形隨鼠標(biāo)移動的方法
這篇文章主要介紹了python開發(fā)之tkinter實現(xiàn)圖形隨鼠標(biāo)移動的方法,涉及Python基于tkinter繪圖的相關(guān)實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11