Search code examples
djangorestjwt

Django REST Authentication credentials were not provided


I'm developing an API using Django Rest Framework. but when i'm trying to access the console gives me this error:

@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def get_all_messages(request, user_id):
    messages = Message.objects.filter(receiver_id=user_id)
    serializer = MessageSerializer(messages, many=True)
    return Response(serializer.data)

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView


urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('admin/', admin.site.urls),
    path('api/get-all-messages/<int:user_id>/', get_all_messages),
]
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [  # Corrected typo here
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

http://localhost:8000/api/token/ copy the token

I have searched but they say to change the REST_FRAMEWORK's AUTHENTICATION PERMISSIONS which I have done as you can see, but to no avail.


Solution

  • rest_framework_simplejwt Tokens cannot be Authenticated by rest_framework TokenAuthentication!

    Use rest_framework_simplejwt JWTAuthentication to Authenticate.

    REST_FRAMEWORK = {
        # •••
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ]
        # •••
    }

    If you want to use a different Authentication mechanism for a specific view, that’s when you use decorators like this:

    @authentication_classes([TokenAuthentication])

    If you don’t need it don’t use it!


    I would recommend the getting started guide. [simple-jwt]