Search code examples
pythondjangodjango-rest-frameworkwebsocketdjango-channels

WebSocket django channels doesn't work with postman


Django Channels Throw error with postman while working well with Html.

I'm following Django Socket Tutorial

"here's the error showing in Django".

WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504]

"Error showing in postman when connecting to ws://127.0.0.1:8000/ws/chat/roomName/"

Sec-WebSocket-Version: 13
Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000

My Code asgi.py

django_asgi_app = get_asgi_application()

import digital_signage.playlist_management.routing

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns))
        ),
    }
)

consumer.py

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        print("self", self)
        self.accept()

Solution

  • Stepping through the \channels\security\websocket.py module, Channels's OriginValidator is looking for an origin header, not a hosts header, which is what Postman defaults to.

    Assuming your ALLOWED_HOSTS looks like:

    ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
    

    Then in Postman, in headers add:

    origin:http://127.0.0.1:8000
    

    And that will pass the origin validator without needing to modify allowed hosts in Django or the ASGI config.