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:
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?
Grazie! Ho salvato la mia giornata. –
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)) –