Dj-rest-auth How to authenticate user with REST_USE_JWT = True when testing

I have Django Rest Framework site that use dj-rest-auth as authentication. I enable REST_USE_JWT = True in my settings.py. I want to test some API that require rest_framework.permissions.IsAuthenticated. I create client with rest_framework.test.APIClient() in my test. I try to login and view some API, but i got HTTP_401_UNAUTHORIZED. I try to login with post username, email, and password to dj-rest-auth login url, and got response access_token, refresh_token, etc. Then use credentials() to include it in header. But the client still got HTTP_401_UNAUTHORIZED. I don't know if i am doing it right. Please help me to authenticate the client in test. Thanks in advance!

class ProfileTests(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.username = "test"
        cls.email = "test@test.com"
        cls.password = "test"
        cls.user = get_user_model().objects.create_user(
            username=cls.username,
            email=cls.email,
            password=cls.password,
        )

        cls.authenticated_client = APIClient()
        response = cls.authenticated_client.post(
            reverse("rest_login"),
            {
                "username": cls.username,
                "email": cls.email,
                "password": cls.password,
            },
            format="json"
        )
        cls.authenticated_client.credentials(HTTP_AUTHORIZATION=settings.JWT_AUTH_COOKIE + " " + response.data["access_token"])

You can login through dj-rest-auth login url called rest_login and then get the access_token. After that you can use credentials() method from rest_framework.test.APIClient. This method can be used to set headers that will then be included on all subsequent requests by the test client. Here is the example

cls.authenticated_client = APIClient()
response = cls.authenticated_client.post(
    reverse("rest_login"),
    {
        "username": cls.username,
        "password": cls.password,
    },
    format="json"
)
cls.authenticated_client.credentials(HTTP_AUTHORIZATION="Bearer " + response.data["access_token"])

Notice that it use Bearer as Authorization header instead of Token. In order to clear the header just call credentials() with no parameter example cls.authenticated_client.credentials(). If you have another way to authenticate user during test with dj-rest-auth, feel free to add your answer in this questions

Back to Top