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 = "[email protected]"
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 theaccess_token
. After that you can usecredentials()
method fromrest_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 exampleNotice that it use
Bearer
as Authorization header instead ofToken
. In order to clear the header just callcredentials()
with no parameter examplecls.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