2015-10-11 11 views
5

L'autenticazione basata su JWT funziona bene utilizzando le richieste POST inviate da dispositivi mobili e "client di riposo avanzato", tuttavia non riesce quando si utilizza il client di prova Django. Il client riceve il token correttamente quando richiesto, ma ottiene la seguente risposta quando tenta di accedere a una vista limitata usando quel token.Come testare l'autenticazione usando REST Framework JWT?

"Le credenziali di autenticazione non sono state fornite."

Il banco di prova:

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.") 

richiesta in uscita dal client di prova: enter image description here

La vista ristretta:

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') 

mi sto perdendo qualcosa dal banco di prova?

risposta

9

Okay, il seguente sembra aver risolto il problema:

Invece di:

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

ho dovuto scrivere:

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

autenticazione funziona ora attraverso il client di prova Django come bene.

+0

Grazie! Ho salvato la mia giornata. –

+0

Stavo usando l'API di Django Rest con autenticazione token e ho richiesto di cambiarlo in: response = self.client.get ('/ api/someurl', {}, HTTP_AUTHORIZATION = 'Token {}'. Format (self.token)) –

0

Può essere utile notare che, quando si utilizza JWT tramite OAuth2, il seguente codice crea le credenziali di autenticazione:

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

Django Resto quadro, tuttavia, include ponteggi per autenticare una richiesta: http://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

Inoltre, ci sono alcuni test interessanti qui: https://github.com/jpadilla/django-jwt-auth/blob/master/tests/test_mixins.py