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

 

客戶端用戶發送    POSThtml

服務器端設置cookie    csrf_token隨機ajax

客戶端攜帶上csrf_token發送請求django

get請求的時候須要設置服務器

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

後臺畝設置set_cookie和csrf_token:post

01-模板標籤方式ui

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

02-裝飾器spa

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_tokencode

# 中間件的設置

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'));
      }
    }
  });
});
相關文章
相關標籤/搜索