Django rest framework + simple JWT - permission classes always enabled

Viewed 1641

I'm using simple JWT for authentication in my rest API.

In my function based views, I use @permission_classes([IsAuthenticated]) to define that the JWT token is required to access that view.

However, I have some views that are not supposed to require the authentication token, therefore I didn't insert the @permission_classes([IsAuthenticated]), but when I test the view it still requires the token.

Here's an example:

@api_view(['POST'])
def userCreate(request):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(status=201)
    
    return Response(serializer.errors, status=400)

When I try to access this view the server replies with a 401 and says:

{
    "detail": "Authorization header must contain two space-delimited values",
    "code": "bad_authorization_header"
}

In my settings.py file I set:

...
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}
2 Answers

I have faced a similar problem when using simple JWT. As I understand Django's permission classes only effect it's standart authentication classes.

Setting the default authentication classes to JWTAuthentication as you did in setting.py file makes every view require a JWT. So you can only disable JWT authentication for a view by setting its authentication_classes to an empty list. You can do so by:

Function based views:

@api_view(['POST'])
@authentication_classes([])
def MyFunctionView():
...

Class based views:

class MyClassView(APIView):
    authentication_classes = []

This way you remove the authentication requirement from a view completely rather than allowing certain types of users but it serves the same purpose for this case.

you can use allow any in the function where you want any user to access that view

from rest_framework.permissions import AllowAny

@permission_classes([AllowAny])

Related