1

所以我有 django tastepie 和 jquery ajax post 基本身份验证的这个实现,它可以工作:

美味派:

class RatingResource(ModelResource):
    city = fields.ForeignKey(CityResource, 'city')
    user = fields.ForeignKey(UserResource, 'user')
    class Meta:
        queryset = Rating.objects.all()
        resource_name = 'rating'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

询问:

  $.ajax({
    type: 'POST',
    url: url,
    data: data,
    crossDomain: true,
    beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', make_base_auth('yuri','y')); 
    },
    success: function (){
        alert("200"); 
    },
    contentType:'application/json',
    dataType: 'application/json',
    processData: false,
  });

我的问题是,我如何编写自己的自定义身份验证?

我试图遵循这一点:http : //django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization 但我得到了一个未经处理的 401。这是我失败的尝试:

class SillyAuthentication(BasicAuthentication):
    def is_authenticated(self, request, **kwargs):
        if 'test' in request.user.username:
          return True

        return False

    # Optional but recommended
    def get_identifier(self, request):
        return request.user.username

class RatingResource(ModelResource):
    city = fields.ForeignKey(CityResource, 'city')
    user = fields.ForeignKey(UserResource, 'user')
    class Meta:
        queryset = Rating.objects.all()
        resource_name = 'rating'
        authentication = SillyAuthentication()
        authorization = DjangoAuthorization()


function make_base_auth(user, password) {
            var tok = user + ':' + password;
            var hash = btoa(tok);
            return "Silly " + hash;
          }
  $.ajax({
    type: 'POST',
    url: url,
    data: data,
    crossDomain: true,
    beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', make_base_auth('yuri','y')); 
    },
    success: function (){
        alert("200"); 
    },
    contentType:'application/json',
    dataType: 'application/json',
    processData: false,
  });

如何使用自定义身份验证调整我的代码?

4

0 回答 0