How to test authentication using REST Framework JWT?

640 views
Skip to first unread message

Márton Széles

unread,
Oct 11, 2015, 12:03:25 PM10/11/15
to Django users

JWT based authentication works well using POST requests sent from mobile and "advanced rest client", however it fails when using the Django test client. 

The client successfully receives the token when requested, but it gets the following response when trying to access a restricted view using that token:


"Authentication credentials were not provided."

Here is my 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.")
My restricted 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')

The outgoing request contains the following headers:




Does anybody know, if there's a particular reason why it works from mobile/browser, but doesn't work with the test client?

Márton Széles

unread,
Oct 11, 2015, 12:20:27 PM10/11/15
to Django users
It seems like this solved the issue: instead of "Authorization", I had to include "HTTP_AUTHORIZATION" for the header key.

response = self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='JWT {}'.format(token)) 
Reply all
Reply to author
Forward
0 new messages