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

學(xué)無先后,達者為師

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

解析django的csrf跨站請求偽造_python

作者:等日落 ? 更新時間: 2022-10-13 編程語言

1.什么是跨站請求偽造

請看圖:

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

然后,銀行也不知道,因為拿到的表單是正規(guī)表單一模一樣的,就給我們轉(zhuǎn)了賬!!

2.如何規(guī)避跨站請求偽造(csrf校驗)

一般后端都會自帶一個csrf校驗,就是在給前端的form表單一個唯一的標(biāo)識,form表單提交給后端,后端需要校驗這個唯一標(biāo)識,不符合就拒絕請求!!返回403(forbidden)

3.如何符合csrf校驗

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

3.1 form表單如何符合校驗

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

3.2 ajax如何符合校驗

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

ajax通過csrf校驗的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)我們在django中注釋掉csrf的中間件時,就表示網(wǎng)站所有的post請求都不進行校驗;打開csrf中間件時,就表示對于所有的post請求都需要進行校驗!

這是,我們思考兩個問題:

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

這時,我們需要引入兩個裝飾器!

4.1 針對FBV的csrf裝飾器

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

# @csrf_exempt   #在打開csrf時對局部視圖函數(shù)不進行校驗
# @csrf_protect  #在關(guān)閉csrf時對局部視圖函數(shù)進行校驗
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 針對CBV的csrf裝飾器

from django.views import View

# @method_decorator(csrf_protect,name='post')  # 針對csrf_protect 第二種方式可以
# @method_decorator(csrf_exempt,name='post')  # 針對csrf_exempt 第二種方式不可以
@method_decorator(csrf_exempt,name='dispatch')
class MyCsrfToken(View):
    # @method_decorator(csrf_protect)  # 針對csrf_protect 第三種方式可以
    # @method_decorator(csrf_exempt)  # 針對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)  # 針對csrf_protect 第一種方式可以
    # @method_decorator(csrf_exempt)  # 針對csrf_exempt 第一種方式不可以
    def post(self,request):
        return HttpResponse('post')
		
csrf_protect  需要校驗
    針對csrf_protect符合我們之前所學(xué)的CBV裝飾器的三種玩法
csrf_exempt   忽視校驗
    針對csrf_exempt只能給dispatch方法加才有效

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

欄目分類
最近更新