提交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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值