Search code examples
pythondjangodjango-rest-frameworkdjango-authenticationdjango-rest-knox

Django restframework, Authentication credentials were not provided, knox-tokenauthentication


I took a tutorial in Redox and Django from youtube from Traversy Media. I follow along with the tutorial and now I don't know were it curshed.

curl http://localhost:8000/api/auth/login/ -d \
'{"username": "Tom", "password": "PassWord@321"}' \
-H "Content-type: application/json" -X POST

By doing so I need to get user and the corresponding token but instead I'm getting

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

What all I did =>

# settings.py

INSTALLED_APPS = [
    'leads',
    'rest_framework',
    'frontend',
    'accounts',
    'knox',
    'django.contrib.admin', 
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ),
}
# serializers.py

class LoginSerializer(serializers.Serializer):
   username = serializers.CharField()
   password = serializers.CharField()

   def validate(self, data):
      user = authenticate(**data)
      if user and user.is_active:
         return user
      raise serializers.ValidationError("Incorrect Credentials")
# api.py

class LoginAPI(generics.GenericAPIView):
   serializer_class = LoginSerializer

   def post(self, request, *args, **kwargs):
      serializer = self.get_serializer(data = request.data)
      serializer.is_valid(raise_exception = True)
      user = serializer.validated_data
      _, token = AuthToken.objects.create(user)
      return Response({
         "user": UserSerializer(user, context = self.get_serializer_context()).data,
         "token": token
      })

# leadmanager/urls.py

urlpatterns = [
    path("api/auth/", include("accounts.urls")),
]

# accounts/urls.py
urlpatterns = [
   path("login/", LoginAPI.as_view()),
]

I don't know were it crushed.


Solution

  • Please add this code

    class LoginAPI(generics.GenericAPIView):
       serializer_class = LoginSerializer
       permission_classes = () # empty tuple 
    
       ...........
    

    Here you need to override permission_classes for LoginAPI view as permission_classes are responsible to check whether the request is authenticated. As LoginAPI is exposed for all users that View has no permission check.