[Django]-What's the proper way to test token-based auth using APIRequestFactory?

34👍

I found a way to get the test to pass, but please post if you have a better idea of how to handle any of this.

request = self.factory.get('/my_endpoint', HTTP_AUTHORIZATION='Token {}'.format(self.token))
force_authenticate(request, user=self.user)

After changing the above two lines of the test, it seems to authenticate based on the token properly.

10👍

I wanted to test the authentication function itself, so forcing authentication wans’t an option.

One way to properly pass the token is to use APIClient, which you already have imported.

client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
response = client.get('/api/vehicles/')

That sets your given token into the request header and lets the back end decide if it’s valid or not.

6👍

Sorry for digging this old thread up, but if someone is using APIClient() to do their tests you can do the following:

from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User


class VehicleCreationTests(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_superuser('admin', 'admin@admin.com', 'admin123')
        self.token = Token.objects.create(user=self.user)

    def testcase(self):
        self.client.force_login(user=self.user)
        response = self.client.post('/api/vehicles/', data=vehicle_data, format='json', HTTP_AUTHORIZATION=self.token)
        self.assertEqual(response.status_code, 201)

Really good resource that I’ve used to come up with this is django-rest-framework-jwt tests

-1👍

The simpler way to force_authentication using a built-in method from APITestCase is:

class Test(APITestCase):
    def setUp(self):
        user1 = User.objects.create_user(username='foo')
        self.client.force_authenticate(user=user1) # self.client is from APITestCase

    ... the rest of your tests ...

Leave a comment