SessionAuthentication在Tastypie中是否适用于HTTP POST? [英] Does SessionAuthentication work in Tastypie for HTTP POST?

查看:131
本文介绍了SessionAuthentication在Tastypie中是否适用于HTTP POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用GET来处理SessionAuthentication和Tastypie,而不必将 content-type application / json 。 HTTP POST尽管头文件中的Cookie具有会话标识,但仍然失败。它与401授权读者失败,但与授权无关。将SessionAuthentication更改为BasicAuthentication并传递用户名/密码也可以。

I am able to do GET to work with SessionAuthentication and Tastypie without setting any headers except for content-type to application/json. HTTP POST however just fails even though the Cookie in the Header has the session id. It fails with a 401 AuthorizationHeader but it has nothing to do with Authorization. Changing SessionAuthentication to BasicAuthentication and passing username/password works too.

有没有人有过SessionAuthentication可以使用Tastypie使用POST?

Has anyone ever got SessionAuthentication to work with POST with Tastypie?

推荐答案

是的,我已经得到了工作。所有你需要做的是传递csfr令牌:

Yes I have gotten it to work. All you need to do is to pass the csfr token:


SessionAuthentication



此认证方案使用内置的
Django会话来检查用户是否被记录。这通常用于与API所在的同一站点上的JavaScript使用的

SessionAuthentication

This authentication scheme uses the built-in Django sessions to check if a user is logged. This is typically useful when used by Javascript on the same site as the API is hosted on.

它要求用户已登录&有一个活跃的会话。 他们
也必须有一个有效的CSRF标记

It requires that the user has logged in & has an active session. They also must have a valid CSRF token.

这是你在jQuery:

This is how you do that in 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",
    // ...

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

Notice the part that says $.cookie('csrftoken'). It gets the csrf token from a cookie that Django sets.

我有一些问题,Django没有在Firefox和Opera上设置cookie,放置模板您的模板中的标签 {%csrf_token%} 可以解决这个问题。正确的解决方案可能是使用装饰器 ensure_csrf_cookie()

I had some problems with Django not setting the cookie on Firefox and Opera. Putting the template tag {% csrf_token %} in your template solves this. The right solution would probably be to use the decorator ensure_csrf_cookie().

这篇关于SessionAuthentication在Tastypie中是否适用于HTTP POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆