How to authenticate user with Token Auth using DRF and Django Channels?

Viewed 39

I am developing a mobile app with React Native. Using WebSockets I'm able to connect and send data to the backend, Django Channels.

My problems is that I need to authenticate the user with rest_framework Token Authentication but user returns as AnonymousUser

My consumers.py:

class NotificationConsumer(WebsocketConsumer):
    authentication_class = [authentication.TokenAuthentication]
    permission_class = [permissions.IsAuthenticated]
    serializer_class = NotificationSerializer
    queryset = Notification.objects.all()

    def connect(self):
        self.accept()
        from_user = self.scope['user']
        Notification.objects.create(from_user=from_user, channel_name=self.channel_name)

    def receive(self, text_data):
        data = json.loads(text_data)
        from_user = self.scope['user']
        to_user = data['to_user']
        title = data['title']
        body = data['body']
        image = data['image']
        
        user = Notification.objects.filter(to_user=to_user)
        channel_name = user.values("channel_name")

        channel_layer = get_channel_layer()
        channel_layer.send(channel_name, {
            "type": "chat_message",
            "title": title,
            "body": body,
            "image": image
        })
        print(data)

I've seen a few questions that have the same problem but the solutions either are outdated or a bit too confusing to wrap my head around.

Been stuck on this for a couple days, would appreciate any help, thanks!

0 Answers
Related