Django Tastypie基本身份验证无法正常工作

时间:2013-07-18 01:01:24

标签: python django tastypie

我有一个UserResource类,允许一个人对User对象进行API调用。当我尝试使用BasicAuthentication进行身份验证时,它会告诉我访问被拒绝。我正在使用应该能够访问对象的用户名和密码。任何想法为什么BasicAuthentication可能不适合我?

class UserResource(ModelResource):

    class Meta:
        # For authentication, allow both basic and api key so that the key
        # can be grabbed, if needed.
        authentication = MultiAuthentication(
            BasicAuthentication(),
            ApiKeyAuthentication())
        authorization = Authorization()
        resource_name = 'user'

        allowed_methods = ['get', 'patch', 'put', ]
        always_return_data = True
        queryset = User.objects.all().select_related("api_key")
        excludes = ['is_active', 'is_staff', 'is_superuser', 'date_joined',
                'last_login']

    def authorized_read_list(self, object_list, bundle):
        return object_list.filter(id=bundle.request.user.id).select_related()

    def hydrate(self, bundle):
        if "raw_password" in bundle.data:
            raw_password = bundle.data["raw_password"]

        # Validate password
            if not validate_password(raw_password):
                if len(raw_password) < MINIMUM_PASSWORD_LENGTH:
                    raise CustomBadRequest(
                        code="invalid_password",
                        message=(
                            "Your password should contain at least {length} "
                            "characters.".format(length=
                                                 MINIMUM_PASSWORD_LENGTH)))
                raise CustomBadRequest(
                    code="invalid_password",
                    message=("Your password should contain at least one number"
                             ", one uppercase letter, one special character,"
                             " and no spaces."))

            bundle.data["password"] = make_password(raw_password)

        return bundle

    def dehydrate(self, bundle):
        bundle.data['key'] = bundle.obj.api_key.key
        # Don't return `raw_password` in response.
        del bundle.data["password"]
        return bundle

以下是未经过身份验证的单元测试行:

 resp = self.api_client.get('/api/v1/user/2/', format='json', HTTP_AUTHORIZATION='Basic ' + base64.b64encode('johndoe:j0hnd03'))

我知道“johndoe”和“j0hnd03”是正确的用户名和密码。如果我为该用户使用ApiKey方法,它可以正常工作。

我也尝试了以下内容:

resp = self.api_client.get('/api/v1/user/2/', format='json', authentication=self.create_basic(username='johndoe', password='j0hnd03'))

1 个答案:

答案 0 :(得分:0)

I believe that the matter could be in your exclude :
 excludes = ['is_active', 'is_staff', 'is_superuser', 'date_joined',
            'last_login']
try to restrict the exclude field to see what you will get, depending of the users type.