Search code examples
djangodjango-viewsdjango-rest-framework-simplejwt

Django rest framework + simple JWT - permission classes always enabled


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
}

Solution

  • 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])