I am trying to apply JWT token authentication to my Django app. I am following this tutorial https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html
I added these settings
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
Then I added authentication check to api_view
# views.py
@api_view(['GET', 'POST'])
@authentication_classes([authentication.TokenAuthentication])
@permission_classes([permissions.IsAuthenticated])
def task(request):
if request.method == 'POST':
if "type" in request.data:
category_name = request.data["type"]
task = create_task.delay(category_name)
return Response({"message": "Create task", "task_id": task.id, "data": request.data})
else:
return Response({"message": "Error, not found 'type' in POST request"})
Then I have an error:
"Authentication credentials were not provided."
How can I fix the error?
In your view, you are overriding the authentication classes using TokenAuthentication
which in turn requires using Token
instead of JWT
in the Authorization header.
To fix, just remove the @authentication_classes
decorator in your view:
@api_view(['GET', 'POST'])
@permission_classes([permissions.IsAuthenticated])
def task(request):
# ...
This will then cause your view to use the authentication classes in DEFAULT_AUTHENTICATION_CLASSES
setting.
Alternatively, if you want to keep using the decorator, just make sure you are using the correct authentication class:
from rest_framework_simplejwt import authentication
@api_view(['GET', 'POST'])
@authentication_classes([authentication.JWTAuthentication]) # correct auth class
@permission_classes([permissions.IsAuthenticated])
def task(request):
# ...