Django在Tasty Pie Session身份验证中的多重身份验证问题不起作用

时间:2013-06-20 14:42:35

标签: python django tastypie django-permissions

我正试图让'多重身份验证'在Tasty Pie中运行。到目前为止, ApiKeyAuthentication()可以进行外部调用,但是当我在自己的Django网站“ SessionAuthentication ”(API托管在同一网站上)上使用API​​时,它会失败尽管用户已登录,但身份验证仍然存在。

我错过了什么吗?

多重身份验证上的美味Pie Doc here

我的资源:

class CommonMeta:
    """
    Based Mata to which all other model resources extend/inherit.
    """
    # MultiAuthentication is used here, wraps any number of other authentication classes,
    # attempting each until successfully authenticating.
    authentication = MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication())
    authorization = UserObjectsOnlyAuthorization()



class ContactResource(MultipartResource, ModelResource):
    class Meta(CommonMeta):
        queryset = Contact.objects.all()
        resource_name = 'contacts'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get', 'put', 'post']
        excludes = ['id']

我的AJAX请求:

 $.ajax({
          url: '/api/v1/contacts/' + id + "/",
          type: 'PUT',
          data: {"company": "test"},

          // On success.
          success: function(data) {
            alert('Load was performed.');
          }

       });

    };

1 个答案:

答案 0 :(得分:1)

我认为它应该正常工作,你可能刚刚错过了关于Tasty Pie docs的一个重要说明

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

您需要为SessionAuthentication传递有效的CSRF令牌才能正常工作。

以下是一个例子:

首先设置一个函数来发送带有每个ajax请求的csrftoken

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

然后在你的ajax设置上:

 $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
                }
            }
        });

模板中的最后一项内容不要忘记包含 {%csrf_token%} 标记!