How to test authentication with REST Framework JWT?

JWT-based authentication works well using POST requests sent from the mobile and "advanced leisure client", but this fails when using the Django test client. The client successfully receives a token on request, but receives a response when trying to access a limited view using this token.

"Authentication credentials were not provided."

Test case:

def test_get_token(self): response = self.client.post("/auth/api/get_token/", {"username": "Heffalumps", "password": "Woozles"}) self.assertEqual(response.status_code, 200, "The token should be successfully returned.") response_content = json.loads(response.content.decode('utf-8')) token = response_content["token"] # The following request fails response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token) response_content = json.loads(response.content.decode('utf-8')) self.assertEqual(response_content["authenticated"], "mooh", "The user should be able to access this endpoint.") 

Outgoing request from the test client: enter image description here

Limited view:

 class RestrictedView(APIView): permission_classes = (permissions.IsAuthenticated, ) authentication_classes = (JSONWebTokenAuthentication, ) def post(self, request): response_data = json.dumps({"authenticated": "mooh"}) return HttpResponse(response_data, content_type='application/json') 

Am I missing something from the test case?

+5
source share
2 answers

Well, it looks like the problem is resolved:

Instead:

 response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token) 

I had to write:

 response = self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='JWT {}'.format(token)) 

Now authentication is also performed through the Django test client.

+9
source

It may be useful to note that when using JWT through OAuth2, the following code creates credentials for authentication:

 self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='Bearer {0}'.format(token)) 

The Django Rest Framework, however, includes scaffolding to authenticate the request: http://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

In addition, there are several interesting tests here: https://github.com/jpadilla/django-jwt-auth/blob/master/tests/test_mixins.py

0
source

Source: https://habr.com/ru/post/1233468/


All Articles