Alex
Alex

Reputation: 732

Django: Token Authentication isn't working with @api_view

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."

for the following request: enter image description here

How can I fix the error?

Upvotes: 0

Views: 1952

Answers (2)

Srijan113
Srijan113

Reputation: 59

I think you are sending JWT as token in header but i think you need to have Bearer token. Try Changing may be that should work. enter image description here

Upvotes: 2

Brian Destura
Brian Destura

Reputation: 12068

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):
    # ...

Upvotes: 2

Related Questions