request.user returns AnonymousUser

I’m trying to write a basic POST request that uses request.user but it sends an AnonymousUser, even though the request requires a token authentication to pass.

views.py:

@api_view(['POST', 'DELETE'])
def like(request, id, *args, **kwargs):
    """
    CRUD for a like
    """
    # Called when a user swipes right
    if request.method == 'POST':
        print(request.user)
        payload = {
            'source': request.user.id,
            'target': id,
        }
        serializer = LikeSerializer(data=payload)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

When I run print(request.user), I get in the output: AnonymousUser.

We’d need to see the code related to the authentication and token generation to try and diagnose this.

This is the CreateTokenView from views.py:

class CreateTokenView(ObtainAuthToken):
    """Create a new auth token for user"""
    serializer_class = AuthTokenSerializer
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

This is the AuthTokenSerializer in serializers.py:

class AuthTokenSerializer(serializers.Serializer):
    """Serializer for the user auth token"""
    email = serializers.EmailField()
    password = serializers.CharField(
        style={'input_type': 'password'},
        trim_whitespace=False,
    )

    def validate(self, attrs):
        """Validate and authenticate the user"""
        email = attrs.get('email')
        password = attrs.get('password')
        user = authenticate(
            request=self.context.get('request'),
            username=email,
            password=password,
        )
        if not user:
            msg = _('Unable to authenticate with provided credentials')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs

I think the first thing I’d check would be to verify that the proper entry was being added to the Token model. I would think that this information may help identify whether the issue is involved with the generation of the token or if its in the subsequent authentication.

I just checked for the token through psql and it appears that the token is currently in the authtoken_token table.