日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

解析django的csrf跨站請(qǐng)求偽造_python

作者:等日落 ? 更新時(shí)間: 2022-10-13 編程語(yǔ)言

1.什么是跨站請(qǐng)求偽造

請(qǐng)看圖:

我們自行寫(xiě)了一個(gè)網(wǎng)站模仿中國(guó)銀行,用戶(hù)不知道是否是真的中國(guó)銀行,并且提交了轉(zhuǎn)賬信息,生成一個(gè)form表單,向銀行服務(wù)器發(fā)送轉(zhuǎn)賬請(qǐng)求,這個(gè)form表單和正規(guī)銀行網(wǎng)站的form表單一模一樣,只不過(guò)里面隱藏著改變了轉(zhuǎn)賬人的信息,改成了我們自己!!

然后,銀行也不知道,因?yàn)槟玫降谋韱问钦?guī)表單一模一樣的,就給我們轉(zhuǎn)了賬!!

2.如何規(guī)避跨站請(qǐng)求偽造(csrf校驗(yàn))

一般后端都會(huì)自帶一個(gè)csrf校驗(yàn),就是在給前端的form表單一個(gè)唯一的標(biāo)識(shí),form表單提交給后端,后端需要校驗(yàn)這個(gè)唯一標(biāo)識(shí),不符合就拒絕請(qǐng)求!!返回403(forbidden)

3.如何符合csrf校驗(yàn)

在我們自己寫(xiě)的正規(guī)網(wǎng)站,我們就需要在前端寫(xiě)一些標(biāo)識(shí),這個(gè)標(biāo)識(shí)是告訴后端,這個(gè)請(qǐng)求是正確的,是我們正規(guī)的網(wǎng)站發(fā)出的,不是釣魚(yú)網(wǎng)站!!

3.1 form表單如何符合校驗(yàn)

在需要提交的form表單里的任意位置加上{% form_token %},這時(shí)就符合了校驗(yàn)!

3.2 ajax如何符合校驗(yàn)

// 第一種 利用標(biāo)簽查找獲取頁(yè)面上的隨機(jī)字符串
data:{"username":'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}
// 第二種 利用模版語(yǔ)法提供的快捷書(shū)寫(xiě)
data:{"username":'jason','csrfmiddlewaretoken':'{{ csrf_token }}'}
// 第三種 通用方式直接拷貝js代碼并應(yīng)用到自己的html頁(yè)面上即可
data:{"username":'jason'}

ajax通過(guò)csrf校驗(yàn)的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));
}

$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

4.csrf相關(guān)的裝飾器

當(dāng)我們?cè)赿jango中注釋掉csrf的中間件時(shí),就表示網(wǎng)站所有的post請(qǐng)求都不進(jìn)行校驗(yàn);打開(kāi)csrf中間件時(shí),就表示對(duì)于所有的post請(qǐng)求都需要進(jìn)行校驗(yàn)!

這是,我們思考兩個(gè)問(wèn)題:

1.網(wǎng)站整體都不校驗(yàn)csrf,就單單幾個(gè)視圖函數(shù)需要校驗(yàn)怎么辦
2.網(wǎng)站整體都校驗(yàn)csrf,就單單幾個(gè)視圖函數(shù)不校驗(yàn)怎么辦

這時(shí),我們需要引入兩個(gè)裝飾器!

4.1 針對(duì)FBV的csrf裝飾器

from django.views.decorators.csrf import csrf_protect,csrf_exempt
from django.utils.decorators import method_decorator

# @csrf_exempt   #在打開(kāi)csrf時(shí)對(duì)局部視圖函數(shù)不進(jìn)行校驗(yàn)
# @csrf_protect  #在關(guān)閉csrf時(shí)對(duì)局部視圖函數(shù)進(jìn)行校驗(yàn)
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')

4.2 針對(duì)CBV的csrf裝飾器

from django.views import View

# @method_decorator(csrf_protect,name='post')  # 針對(duì)csrf_protect 第二種方式可以
# @method_decorator(csrf_exempt,name='post')  # 針對(duì)csrf_exempt 第二種方式不可以
@method_decorator(csrf_exempt,name='dispatch')
class MyCsrfToken(View):
    # @method_decorator(csrf_protect)  # 針對(duì)csrf_protect 第三種方式可以
    # @method_decorator(csrf_exempt)  # 針對(duì)csrf_exempt 第三種方式可以
    def dispatch(self, request, *args, **kwargs):
        return super(MyCsrfToken, self).dispatch(request,*args,**kwargs)

    def get(self,request):
        return HttpResponse('get')

    # @method_decorator(csrf_protect)  # 針對(duì)csrf_protect 第一種方式可以
    # @method_decorator(csrf_exempt)  # 針對(duì)csrf_exempt 第一種方式不可以
    def post(self,request):
        return HttpResponse('post')
		
csrf_protect  需要校驗(yàn)
    針對(duì)csrf_protect符合我們之前所學(xué)的CBV裝飾器的三種玩法
csrf_exempt   忽視校驗(yàn)
    針對(duì)csrf_exempt只能給dispatch方法加才有效

原文鏈接:https://www.cnblogs.com/suncolor/p/16587106.html

欄目分類(lèi)
最近更新