自定义身份验证在 django-tastypie 中不起作用

custom authentication not working in django-tastypie

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

我试着遵循这个: http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization

我已经实现了基本方法,

api.py

def prepareResponce(responceData):
    """Prepares a Json responce with status 200"""
    response = JsonResponse(responceData)
    return response  # {"foo": "bar"}

class CustomBasicAuthentication(BasicAuthentication):
    userID = None
    userType = None
    userAccess = None
    userName = None

    def is_authenticated(self, request, **kwargs):
        if 'admin' in request.user.username:
             return prepareResponce({'logged in': 'Admin' })
                  #return True
        return prepareResponce({'not allowed for':userName })


    def get_identifier(self, request):
        return request.user.username


class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        authentication = CustomBasicAuthentication()
        allowed_methods = ['get', 'post']

当我调用 API 提供管理员的用户名和密码时,它总是 return 其他部分。 我哪里做错了?

您错过了 return 并且您没有调用父 is_authenticated 函数:

def is_authenticated(self, request, **kwargs):
    super(CustomBasicAuthentication, self).is_authenticated(request, **kwargs)
    if 'admin' == request.user.username:
         return prepareResponce({'logged in': 'Admin' })
    return prepareResponce({'not allowed for': self.userName })