2013-07-18 72 views
1

我有一個UserResource類,允許某人對用戶對象進行API調用。當我嘗試使用BasicAuthentication進行身份驗證時,它告訴我訪問被拒絕。我正在使用應該能夠訪問對象的用戶名和密碼。任何想法爲什麼BasicAuthentication可能不適合我?Django Tastypie基本身份驗證不起作用

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')) 

回答

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. 
+0

我刪除了排除,但這並沒有改變任何東西。我仍然獲得401身份。 ApiKey的工作原理是沒有意義的,爲什麼BasicAuthentication不起作用。 – Dan

相關問題