2011-05-20 105 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

相关问题