'How to use custom authentication class inside ListAPIView

I am using react components and to test my code I wrote a quick custom authentication class and defined in the settings for the rest_framework as follow:

DEFAULT_AUTHENTICATION_CLASSES += ['restaurant.rest_api.dev.DevAuthentication']

This works great and uses the user I tell it to

class DevAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        user = User.objects.get(id=6)
        return (user,None)

However, I am now trying to use ListAPIView from generics and the user that prints out is an anonymous user which means that it is not using my authentication class. I found that classes can be explicitly defined inside the function and so I did

class SearchUsersAPIView(generics.ListAPIView):
    search_fields = ['email', 'first_name', 'last_name', 'phone_number']
    filter_backends = (filters.SearchFilter,)
    queryset = CustomUser.objects.all()
    authentication_classes = [restaurant.rest_api.dev.DevAuthentication]
    serializer_class = userSerializer
    @permission_classes([IsAuthenticated])
    def dispatch(self,request, *args, **kwargs):
        self.request = request
        print(self.request.user)
        if request.user.is_anonymous or request.user.is_user_superuser()==False: 
            response = Response({"message":"Action Denied"}, status = status.HTTP_400_BAD_REQUEST)
            response.accepted_renderer = JSONRenderer()
            response.accepted_media_type = "application/json"
            response.renderer_context = {}
            return response
        return super().dispatch(request,*args, **kwargs)

I must add that if I write a simple function view with the api_view decorator the user authenticated is the one that I have specified. I wonder why this is not working only for this class and uses its defaults which are basic and session authentication. Is there a way to achieve what I want? I added a view right above and it seems to work fine:

@api_view(['GET'])
def search_users_view(request):
    print(request.user)
    return Response({"message":"Action Denied"}, status = status.HTTP_200_OK)


Solution 1:[1]

system shows the anonymous user when it fails to check the authentication of users per view, so you can try adding

permission_classes=[IsAuthenticated]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ranu Vijay