Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django test client http basic auth for post request

everyone. I am trying to write tests for RESTful API implemented using django-tastypie with http basic auth. So, I have the following code:

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 request is done well, returning status code 200. But POST request always returns 401. I am sure I am doing something wrong. Any advice?

like image 660
dmrz Avatar asked May 20 '11 07:05

dmrz


1 Answers

Check out this question. I've used that code for tests using both GET and POST and it worked. The only difference I can see is that you have used base64.encodestring instead of base64.b64encode.

Otherwise, if that doesn't work, how are you performing the HTTP Authentication? I wrote and use this function decorator:

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
like image 106
Humphrey Avatar answered Nov 05 '22 05:11

Humphrey