Django csrf校驗

引入:css

一般,釣魚網站本質是本質搭建一個跟正常網站如出一轍的頁面,用戶在該頁面上完成轉帳功能html

轉帳的請求確實是朝着正常網站的服務端提交,惟一不一樣的在於收款帳戶人不一樣。前端

若是想模擬一個釣魚網站,就但是給用戶書寫一個form表單 對方帳戶的input框沒有name屬性,而後你本身悄悄提早寫好了一個具備默認的而且是隱藏的具備name屬性的input框。jquery

若是想解決這個問題,當轉帳請求發送給服務端後,服務端會給各臺機器返回一個隨機實時字符串。下一次,若是還有請求向服務端發時,服務端會校驗字符串,若對不上的話服務端就拒絕訪問。這就是csrf校驗。ajax

那麼form表單如何進行csrf校驗呢?django

你只須要在你的form表單內寫一個{% csrf_token %}就能夠了bootstrap

Ajax請求設置csrf_token的三種方式

 示例:cookie

urls.pyide

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));
}
myfile.js

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 轉帳 %s元' %(username,target_user,money))
    return render(request,'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 href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" 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">發送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>
transfer.html

csrf裝飾器

csrf裝飾器做用在FBV上

裝飾器模塊導入:

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

當咱們網站總體都校驗csrf的時候 我想讓某幾個視圖函數不校驗

@csrf_exempt #給哪一個視圖函數加上,就不給哪一個視圖校驗csrf

當咱們網站總體都不校驗csrf的時候 我想讓某幾個視圖函數校驗

@csrf_protect  #給哪一個視圖函數加上,就給哪一個視圖校驗csrf

注意:驗證同時須要把'django.middleware.csrf.CsrfViewMiddleware'註銷掉

csrf裝飾器做用在CBV上

當咱們網站總體都不校驗csrf的時候 我想讓某幾個視圖函數校驗

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'註銷掉

當咱們網站總體都校驗csrf的時候 我想讓某幾個視圖函數不校驗

 總結:給CBV加裝飾器 推薦使用模塊method_decorator

csrf_exempt 只能給dispatch方法裝

相關文章
相關標籤/搜索