Python-django中ajax使用POST时使用csrf_token

环境:django1.6.5 python 2.6/2.7

django对POST请求需要csrf_token验证,后端会检测前端发过来的token,如果有问题可以会出现403Forbidden的错误。

这个token是由后端在页面GET请求页面文件的时候就放进去的,可以在模板中使用{% csrf_token %},例如表单的POST请求就可以这个做,会生成一个隐藏的表单域,带有后端响应页面时塞进来的随机生成的token值。而ajax的请求可以在HTTP header里把这个值放进去,后端需要响应并返回页面文件时塞进cookie,以便前端可以拿到这个值然后放到Header里再进行POST请求。

对于POST请求,要想前端有token数据,需要几个修饰方法decorator method

from django.views.decorators.csrf import csrf_protect

from django.views.decorators.csrf import requires_csrf_token

from django.views.decorators.csrf import ensure_csrf_cookie
这里使用的是这个,前端可以从cookie里拿到token值
使用的时候在相应的view或者方法上加上

@ensure_csrf_cookie

例如:

from django.views.decorators.csrf import requires_csrf_token
from django.shortcuts import render

@requires_csrf_token
def my_view(request):
    c = {}
    c.update(csrf(request))
    return HttpResponse("value", c)

而要使POST不会检测token可以使用

@csrf_exempt
对于ajax ,前端需要获取token

Javascipt

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // 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 loaddata()
{
    var csrftoken = getCookie('csrftoken');
    var xmlhttp;
    if (window.XMLHttpRequest) {
         // code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            str = xmlhttp.responseText;
            alert(str);
        }
    }
    xmlhttp.open("POST","ajax/",true);
    xmlhttp.setRequestHeader('X-CSRFToken',csrftoken)
    xmlhttp.send();
}

要先open(),再setRequestheader(),然后再send()

JQuery 来自官方文档

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
             var 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;
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
csrftoken = getCookie('csrftoken');
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
$.ajax({url:"ajax/",type:"POST",success:function(result){
    alert(result);
}});
参考:

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

http://www.w3schools.com/JQuery/ajax_ajaxsetup.asp

你可能感兴趣的:(PYTHON,Django,Web前端)