Search code examples
djangodjango-rest-frameworkdjango-authenticationdjango-serializer

Django Rest Framework asking for authentication after sign in


I am able to successfully login via Token Authentication. However, when getting another API, its asking for authentication.

{"detail":"Authentication credentials were not provided."}

views.py

class CreateQuiz(generics.ListCreateAPIView):    
    serializer_class = QuizSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes =(IsAuthenticated,)
        
    def get_queryset(self):    
        return somequeryset

settings.py

REST_FRAMEWORK ={
     'DEFAULT_AUTHENTICATION_CLASSES': (
    'knox.auth.TokenAuthentication',
    ),

}



from datetime import timedelta

REST_KNOX ={
    'USER_SERIALZIER' :'api.serializer.UserSerializer',
    'TOKEN_TTL': timedelta(hours=24*7),
}

when I test http://127.0.0.0.1:8000/apis/v1/login/?username=xxxx.com&password=xxxx on postman, I get succcessfully authenticated and returns

{
    "expiry": "2021-05-18T19:46:33.841420Z",
    "token": "f07a35897b070eabfcf1439c4495b8cede5fd9908135692e2c516127a926f2ab"
}

Solution

  • You have to add the token in the header of all future requests.

    Authorization: Token <your token>
    

    Also, you should use the POST instead of GET because the password will be visible in the URL.