django csrftoken CSRF in several ways

1 Introduction

Before we send data from when the front end to the back end, has been the setting of middleware in the csrftoken this to comment out, in fact, played a major, in order to avoid malicious attack on the protective effect of the data. But this is not directly commented intellectual type of choice, here we introduce several ways to solve this problem.

csrf Principle: transmitting first get request, the user's browser when a random string reservoirs, sending post request, the browser automatically carry the character string to be identified

2. Mode 1

Add {% csrf_token%} in the front end, data transmitted from the data front end ajax add the following:

csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val()

3. Second way

X-CSRFToken added in ajax request header, the value must be fetched from the cookie csrftoken

 $('#login').click(function () {
        $.ajax(
            {
                url:{% url 'login' %},
                type: 'post',
                headers:{ "X-CSRFToken":$.cookie('csrftoken') },
                data: {
                    user: $('[name="user"]').val(),
                    pwd: $('[name="pwd"]').val()
                },
                success: function (data) {
                    data = JSON.parse(data);
                    if (data.status) {
                        window.location = data.url
                    }
                    else {
                        alert('登陆错误')
                    }
                }
            }
        )
    })

4. Three ways
using .ajaxSetup $ () to add the global default parameters ajax

$.ajaxSetup({
        headers: {"X-CSRFToken": $.cookie('csrftoken')},
    });

PS: I encountered a problem no one answer? Requires Python learning materials? Click on the link below you can add yourself get
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

5. Four ways
in view of the need to set a cookie on the decorator added ensure_csrf_cookie ()

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def server(request):

    return render(request, 'server.html')

Guess you like

Origin www.cnblogs.com/python960410445/p/11963981.html