'JWT with Django Rest Framework not working in production

My application uses Django Rest Framework for the APIs and JWT for authenticating the users. Everything was working fine in my local machine. I started having problems after a deployed it to an EC2 instance.

The only things that still work are the login, registration and tokens refresh. That is, when I try to log in, I receive the tokens back from the back-end, which are successfully stored in the local storage; when I try to sign up, the back-end creates the new user; and from time to time the tokens are also successfully updated.

But all the other API calls fail. At the beginning, when I made an API call, I was getting back "401 Unauthorized".

I believe the reason was because Apache wasn't forwarding the Authorization-Headers. So I added "WSGIPassAuthorization On" to the Apache configuration.

Now I am getting "500 Internal Server Error" instead.

As I already said, only API calls to login, tokens refresh and registration are working. For login and tokens refresh, I am using the default "TokenObtainPairView" and "TokenRefreshView".

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('log-in/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('refresh-token/', TokenRefreshView.as_view(), name='token_refresh'),
]

For the registration, this is the view I am using:

class CreateUserAPI(CreateAPIView):
    serializer_class = UserSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        user_taken = User.objects.filter(username=request.data['username']).exists()
        if user_taken:
            return Response({'message': 'username already taken'}, status.HTTP_400_BAD_REQUEST)

        email_taken = User.objects.filter(email=request.data['email']).exists()
        if email_taken:
            return Response({'message': 'email already taken'}, status.HTTP_400_BAD_REQUEST)

        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

This is one of the views that doesn't work:

class DeckApi(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        queryset = Deck.objects.filter(user=request.user)
        serializer = DeckSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

Does anyone know what the problem may be?



Sources

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

Source: Stack Overflow

Solution Source