Skip to content
Advertisement

How to test successful token claim with jwt

I’m using django rest simple jwt and I wanted to test a simple login and check the response data for the token and other custom data.

So I tried with the APITestCase to create an user and then try a login with the same credentials.

The results is a 401 instead a 200 with a token in response data.

Here is my test case simplified:

from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model

# Create your tests here.
User = get_user_model()

class UserAuthTestCase(APITestCase):
    username = "someuser"
    password = "1234pass"


    def setUp(self):
        self.user = User.objects.create(
            username=self.username,
            password=self.password
        )

    def test_successful_login_gives_200(self):
        response = self.client.post(
            '/auth/token/',
            {
                'username': self.username,
                'password': self.password
            },
            format='json'
        )
        self.assertEqual(response.status_code, 200)

The the rest framework configuration is set to use the simplejwt authentication only.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

Advertisement

Answer

When creating the User with User.objects.create you are setting the password without hashing so when you later try to authenticate the user you end up comparing the hashed password value withe the raw unhashed password in the database. Use User.objects.create_user which handles hashing by calling set_password internally.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement