django16: csrf跨站请求伪造/CSRF相关装饰器
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                django16: csrf跨站请求伪造/CSRF相关装饰器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                CSRF
即跨站請求攻擊
跨站請求偽造csrf釣魚網站本質搭建一個跟正常網站一模一樣的頁面用戶在該頁面上完成轉賬功能轉賬的請求確實是朝著正常網站的服務端提交唯一不同的在于收款賬戶人不同給用戶書寫form表單 對方賬戶的input沒有name屬性你自己悄悄提前寫好了一個具有默認的并且是隱藏的具有name屬性的input模擬釣魚網站?
form表單中csrf校驗
<form action="" method="post">{% csrf_token %}old_password:<input type="text" name="old_password">new_password:<input type="text" name="new_password"><input type="submit"></form>?
AJAX csrf校驗
第一種方式:自己手動獲取
$('#d1').click(function () {$.ajax({url:'',type:'post',// 第一種方式 自己手動獲取 data:{'username':'jason','csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},success:function (data) {alert(data)}})})第二種方式:利用模板語法
$('#d1').click(function () {$.ajax({url:'',type:'post',// 第二種方式 利用模板語法data:{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},success:function (data) {alert(data)}})})第三種方式:通用方式 引入外部js文件 官網提供的方式
$('#d1').click(function () {$.ajax({url:'',type:'post',##<script src="{% static 'myset.js' %}"></script>success:function (data) {alert(data)}})})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 protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }$.ajaxSetup({beforeSend: function (xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {xhr.setRequestHeader("X-CSRFToken", csrftoken);}} });?
CSRF相關裝飾器
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator@csrf_exempt # 不校驗csrf @csrf_protect # 校驗使用方法
在視圖函數頭上裝
# @csrf_exempt # 不校驗csrf # @csrf_protect # 校驗, 先注釋中間件scrf def transfer(srequest):return HttpResponse('transfer')CBV 只能在dispatch加
?
class MyHome(View): @method_decorator(csrf_protect) # 第三種 類中所有的方法都裝def dispatch(self, request, *args, **kwargs):return super().dispatch(request,*args,**kwargs)def post(self,request):return HttpResponse('post')def get(self,request):return HttpResponse('get')?
?
?
參考:https://www.cnblogs.com/guyouyin123/p/12194181.html
總結
以上是生活随笔為你收集整理的django16: csrf跨站请求伪造/CSRF相关装饰器的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: django15:中间件
 - 下一篇: django17:importlib应用