SessionAuthentication是否在Tastypie中用于HTTP POST?

Pra*_*kar 6 python django rest tastypie

我能够使用GET与SessionAuthentication和Tastypie一起工作而不设置任何标题,除了content-typeto application/json.然而,即使标头中的Cookie具有会话ID,HTTP POST也会失败.它失败了401 AuthorizationHeader,但它与授权无关.将SessionAuthentication更改为BasicAuthentication并传递用户名/密码也可以.

有没有人用SessionAuthentication与Tastypie一起使用POST?

dan*_*son 10

是的,我已经让它工作了.您需要做的就是传递csfr令牌:

SessionAuthentication

此身份验证方案使用内置的Django会话来检查用户是否已记录.当Javascript在托管API的同一站点上使用时,这通常很有用.

它要求用户已登录并具有活动会话.他们还必须拥有有效的CSRF令牌.

这就是你在jQuery中的表现:

// sending a csrftoken with every ajax request
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});

$.ajax({
    type: "POST",
    // ...
Run Code Online (Sandbox Code Playgroud)

请注意所说的部分$.cookie('csrftoken').它从Django设置的cookie中获取csrf令牌.

更新:

我在Django没有在Firefox和Opera上设置cookie时遇到了一些问题.将模板标记{% csrf_token %}放在模板中可解决此问题.正确的解决方案可能是使用装饰器ensure_csrf_cookie().