Django uses ajax and certification of three ways by csrf

Django uses ajax and certification of three ways by csrf

ajax Features

  1. Partial refresh
  2. Asynchronous request

Django is written in ajax

ajax is encapsulated in jQuery, to use ajax, jQuery first introduced.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>登录页面</h1>
{#<form action="" method="post">#}
{#    {% csrf_token %}#}
{#    用户名: <input type="text" name="username">#}
{#    密码: <input type="text" name="password">#}
{#    <input type="submit">#}
{#</form>#}

{% csrf_token %}
<hr>
用户名: <input type="text" id="uname">
密码: <input type="password" id="pwd">
<button id="sub">提交</button>
<span id="error" style="color:red;font-size: 12px;"></span>
</body>

<!-- jQuery中封装了ajax -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
{#<script src="{% static 'js/xx.js' %}"></script>#}
<script>
    $('#sub').click(function () {

        var uname = $('#uname').val();
        var pwd = $('#pwd').val();
        var csrf_token = $('[name="csrfmiddlewaretoken"]').val();

        $.ajax({
            url: '{% url "login" %}',    // 请求路径
            type: 'post',    // 请求方法
            // 请求数据,不需要携带数据的请求,不需要写data参数
            data: {'uname': uname, 'pwd': pwd, 'csrfmiddlewaretoken': csrf_token},
            success: function (res) {
                console.log('>>>>', res);    // res参数拿到的是响应数据
                if (res !== 'ok') {
                    $('#error').text('用户名或者密码有误!')
                }else {
                    location.href='/home/';
                }
            }
        })
    })
</script>
</html>

CSRF Profile

CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also called: one click attack / session riding, abbreviated: CSRF / XSRF. Jiang attacker via HTTP request data to the server, so the answer to steal cookie. After the answer to steal cookie, an attacker can not only get information about the user, you can also modify the account information associated with the cookie.

So the most straightforward solution to CSRF attacks is to generate a random csrftoken value stored on the user's page, every request with a value over complete verification.

ajax certified by csrf_token

1 way to get through the input tag

After input logic by finding csrf label generation after rendering templates to get csrf token of value.

hmtl Code

ajax may submit data directly, there is no need to wrap the label input in the form tag.

{% csrf_token %} 
用户名: <input type="text" id="uname">
密码: <input type="password" id="pwd">
<button id="sub">提交</button>
js code
$('#sub').click(function () {

    var uname = $('#uname').val();
    var pwd = $('#pwd').val();
    // 获取到{% csrf_token %}这个模板渲染语法渲染之后的input标签对应的值
    var csrf_token = $('[name="csrfmiddlewaretoken"]').val();

    $.ajax({
        url: '{% url "login" %}',  // 127.0.0.1:8000/login/
        type: 'post',
        // 给post请求提交的数据中添加上csrf_token认证所需要的键值对
        data: {'uname': uname, 'pwd': pwd, 'csrfmiddlewaretoken': csrf_token},
           success:function (res) {
        console.log('>>>>',res);
        if (res !== 'ok'){
            $('#error').text('用户名或者密码有误!')

        }else {
            location.href='/home/';
        }
    }
})
})

Mode 2 template rendering direct access

Value csrf_token authentication data portion of the key-value pairs of data written directly

{{ csrf_token }}

After the template rendering, it is the direct value of the input value labels.

html code

Similarly, no need to input tags in the form tag wrapped.

用户名: <input type="text" id="uname">
密码: <input type="password" id="pwd">
<button id="sub">提交</button>
js code
$('#sub').click(function () {

    var uname = $('#uname').val();
    var pwd = $('#pwd').val();

    $.ajax({
        url: '{% url "login" %}',  // 127.0.0.1:8000/login/
        type: 'post',
        // 需要注意的是:经过模板渲染后的内容是不会带引号的,需要我们手动给csrf_token加引号,表示这是一个字符串,否则将会按照变量来解析,从而出错
        data: {'uname':uname,'pwd':pwd,'csrfmiddlewaretoken':'{{ csrf_token }}'},
        success: function (res) {
            console.log('>>>>',res);
            if (res !== 'ok'){
                $('#error').text('用户名或者密码有误!')
            }else {
                location.href='/home/';
            }
        }
    })
})

No jQuery code Cookie packaging operations, we need to first introduced.

<script src="{% static 'jquery.js' %}"></script>
<script src="{% static 'jquery.cookie.js' %}"></script>
<script>
    $('#btn').click(function () {

        var uname = $('[type="text"]').val();
        var pwd = $('[type="password"]').val();
        // var csrf_token = $('[name="csrfmiddlewaretoken"]').val();

        $.ajax({
            url: '/login/',
            type: 'post',
            // data:{uname:uname,pwd:pwd,csrfmiddlewaretoken:csrf_token},
            headers: {'X-CSRFToken': $.cookie('csrftoken')},    // 获取cookie中的csrftoken,将其设置为ajax的请求头
            data: {uname: uname, pwd: pwd},
            success: function (res) {
                console.log(res);
            }
        })
    })
</script>

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521571.html