zoukankan      html  css  js  c++  java
  • Django中关于csrf_token的认证

    一、介绍:

      为了网站网站的安全,防止XSS等恶意数据性攻击。Django中提供了一个模块用以提供csrf认证。在使用之前我们先介绍下在Django中csrf的认证原理。
       csrf原理:在访问是会先发送一个GET的请求,将自己生成的验证字符串存放在客户端的cookie中,当客户端发送POST请求时,需携带该字符串进行认证。

    二.认证方式:

      1.客户端直接post请求认证:

        在前端的form表单中直接添加 {% csrf_token %}便可通过认证

    <form action="/login/" method="POST">
            {% csrf_token %}
            <input type="text" name="user" />
            <input type="text" name="pwd" />
            <input type="submit" value="提交" />
    </form>

      2.客户端用ajax方式提交认证:

       2.1:在ajax中添加X-CSRFToken的请求头,必须从cookie中取csrftoken的值(对单一ajax请求处理)

    $.ajax({
                type: "POST",
                url:"/login/",
                dataType: "json",
                headers: {'X-CSRFtoken': $.cookie('csrftoken')},
                data:{
                    "account_code":$('#account_login').find("input[name=account_code]").val(),
                    "pwd":$.sha256(pwd_const+$('#account_login').find("input[name=pwd]").val()),
                },
                error: function(request) {
                    alert("Connection error");
                },
                success: function(data) {
                    var success = data.status;
                    if (success) {
                        window.location="/login/home/";
                    } else {
                        $("#msg-info").html(data.message).css('color', 'red');
                        $('#msg-info').show();
                    }
                }
            });

     2.2:使用$.ajaxSetup()给全局的ajax添加默认参数

            $.ajaxSetup({
                    beforeSend: function(xhr,settings){
                        xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken'));
                    }
                });

       注意:使用ajax提交数据时,如果我们前端没有csrf_roken的值会验证失败。此时我们还需要在客户端添加一个装饰器ensure_csrf_cookie(),使服务端提前发送csrf_token用以验证

    from django.views.decorators.csrf import ensure_csrf_cookie
    @ensure_csrf_cookie
    def login(request):
        return render(request, 'login.html')
  • 相关阅读:
    表、栈和队列
    POJ 1207 The 3n + 1 problem
    记录一个很低级的错误:command 'usr/local/cuda/bin/vncc' failed with exit status 2
    [转载]Benchmark和baseline的区别
    [转载]神经网络架构搜索(Neural Architecture Search)杂谈
    CNN常用图片分类网络
    [转载]OCR原理
    目标检测、实例分割学习
    [转载]上采样
    自动驾驶资料收集
  • 原文地址:https://www.cnblogs.com/Jack-Kong/p/10149641.html
Copyright © 2011-2022 走看看