提交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'));
      }
    }
  });
});
原文地址:https://www.cnblogs.com/jun-1024/p/10914032.html