提交form表單post時csrf_token的作用(cookie的設置)


 

客戶端用戶發送    POST

服務器端設置cookie    csrf_token隨機

客戶端攜帶上csrf_token發送請求

get請求的時候需要設置

post請求的時候應該已經攜帶csrf_token

后台畝設置set_cookie和csrf_token:

01-模板標簽方式

在form表單中設置  {% csrf_token %}

02-裝飾器

from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator

@method_decorator(ensure_csrf_cookie)
def get(self,request):
    return render(request,'users/login.html')

03-中間件get_token

# 中間件的設置

from django.utils.deprecation import MiddlewareMixin
from django.middleware.csrf import get_token

class MyMiddleware(MiddlewareMixin):
    def process_request(self,request):
        get_token(request)
# 中間件的注冊
MIDDLEWARE = [
    'utils.MyMiddleware.MyMiddleware', ]

 

04-Js發送請求的時候需要添加csrf_cookie

# JS文件后面添加

  // get cookie using jQuery
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      let cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        let 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;
  }

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  // Setting the token on the AJAX request
  $.ajaxSetup({
    beforeSend: function (xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
    }
  });
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM