1

我有一个 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'))
4

1 回答 1

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. 
于 2013-07-18T03:25:11.073 回答