2011-05-20 101 views
7

每個人。我正在嘗試爲使用django-tastypie和http basic auth實現的RESTful API編寫測試。所以,我有以下代碼:Django測試客戶端http基本身份驗證用於發佈請求

def http_auth(username, password): 
    credentials = base64.encodestring('%s:%s' % (username, password)).strip() 
    auth_string = 'Basic %s' % credentials 
    return auth_string 

class FileApiTest(TestCase): 

    fixtures = ['test/fixtures/test_users.json'] 

    def setUp(self): 
     self.extra = { 
      'HTTP_AUTHORIZATION': http_auth('testuser', 'qwerty') 
     } 

    def test_folder_resource(self): 
     response = self.client.get('/api/1.0/folder/', **self.extra) 
     self.assertEqual(response.status_code, 200) 

    def test_folder_resource_post(self): 
     response = self.client.post('/api/1.0/folder/', **self.extra) 
     self.assertNotEqual(response.status_code, 401) 

GET請求已完成,返回狀態代碼200.但POST請求始終返回401。我確信我做錯了什麼。有什麼建議?

+0

也許檢查你的Meta:授權資源?它說什麼? – 2011-05-21 14:05:16

+0

'授權= DjangoAuthorization()' – dmrz 2011-05-25 18:19:34

+2

aw,廢話,我的意思是「身份驗證」這就是你在這裏測試。不同之處在於認證==「你是誰」,授權==「你能做到嗎?」 – 2011-05-25 18:38:32

回答

4

結帳this question。我已經使用該代碼進行了使用GET和POST的測試,並且它工作正常。我可以看到唯一的區別是你已經使用base64.encodestring而不是base64.b64encode。

否則,如果這不起作用,您如何執行HTTP身份驗證?我寫和使用這個功能裝飾:

import base64 
from django.http import HttpResponse 
from django.contrib.auth import authenticate, login 

def http_auth(view, request, realm="", must_be='', *args, **kwargs): 
    if 'HTTP_AUTHORIZATION' in request.META: 
     auth = request.META['HTTP_AUTHORIZATION'].split() 
     if len(auth) == 2: 
      if auth[0].lower() == "basic": 
       uname, passwd = base64.b64decode(auth[1]).split(':') 
       if must_be in ('', uname): 
        user = authenticate(username=uname, password=passwd) 
        if user is not None and user.is_active: 
          login(request, user) 
          request.user = user 
          return view(request, *args, **kwargs) 

    # They mustn't be logged in 
    response = HttpResponse('Failed') 
    response.status_code = 401 
    response['WWW-Authenticate'] = 'Basic realm="%s"' % realm 
    return response 


def http_auth_required(realm="", must_be=''): 
    """ Decorator that requires HTTP Basic authentication, eg API views. """ 
    def view_decorator(func): 
     def wrapper(request, *args, **kwargs): 
      return http_auth(func, request, realm, must_be, *args, **kwargs) 
     return wrapper 
    return view_decorator 
+0

我使用django-tastypie,它內置了bash http身份驗證,並且工作正常。我不僅可以使用django測試客戶端發出請求,我不知道問題出在哪裏 – dmrz 2011-05-25 18:25:48

+0

此文件似乎處理身份驗證。仔細觀察一下,看看你是否可以跟蹤發生了什麼問題? https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authentication.py – Humphrey 2011-05-26 00:05:45

1

我找到了我的問題的原因。 DjangoAuthorization使用django premissions框架檢查權限,因爲我沒有在我的項目中使用它 - 所有來自非超級用戶的post/put/delete請求都是未經授權的。我的錯。

無論如何,非常感謝您,夥計們的迴應。

+0

你是如何解決它的? – 2015-03-18 19:27:21

相關問題