0

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

我错过了什么吗?

多认证的美味馅饼文档在这里

我的资源:

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.');
          }

       });

    };
4

1 回答 1

1

我认为它正在正常工作,您可能只是错过了有关 Tasty Pie 文档的重要说明

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

您需要传递一个有效的 CSRF 令牌才能使 SessionAuthentication 工作。

这是一个例子:

首先设置一个函数来为每个 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 %}标记!

于 2013-06-20T15:05:14.953 回答