Ihor Kram
Ihor Kram

Reputation: 53

WebSocket dosn't work with postman (django channels)

I have a Django project which I run locally on my mac. And I use channels to create websocket connection.

And an interesting thing happened: The web socket works when I try to connect through .html file:

myTemplate.html

const ws = new WebSocket(
                'ws://'
                + window.location.host
                +'/ws/test/?token='
                +'**mytoken**'
            );'

I can send, and receive messages. But the same URL doesn't work in postman or https://websocketking.com/

Firstly, I thought it is because I run server locally. But on real server there is the same problem.

I can create chat from html page, but it's impossible to connect from "outside".

I searched all stackoverflow and implement everything - to no avail.

asgi.py

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev')
django.setup()


from channels.routing import ProtocolTypeRouter,get_default_application
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import path, re_path
from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack





from myapp import consumers, routing

 
application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': AllowedHostsOriginValidator(
        JWTAuthMiddlewareStack(
            URLRouter(
                routing.websocket_urlpatterns
            )
        )
    ),
})

settings

ASGI_APPLICATION = 'spacetime.asgi.application'
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ***
]

vccode console

Django version 4.1.2, using settings 'spacetime.settings.dev'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

vccode console when connecting from html file

HTTP GET /my/socket/view/ 200 [0.01, 127.0.0.1:60258]
WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60260]
WebSocket CONNECT /ws/test/ [127.0.0.1:60260]

xccode console when connectin from https://websocketking.com/

WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60759]
WebSocket REJECT /ws/test/ [127.0.0.1:60759]
WebSocket DISCONNECT /ws/test/ [127.0.0.1:60759]

postman

Request URL: http://127.0.0.1:8000/ws/test/?token=**mytoken**
Request Method: GET
Status Code: 403 Access denied
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 0VRmdvoFhma7lndljwIY6w==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000
Response Headers

token is alright

https://websocketking.com/

Could not connect to "ws://127.0.0.1:8000/ws/test/?token=**mytoken**". You may be able to find more information using Inspector/Dev Tools on this page.

Connecting to ws://127.0.0.1:8000/ws/test/?token=**mytoken**

any ideas why it doesn't work with postman?

Upvotes: 1

Views: 1292

Answers (3)

KeyTamer
KeyTamer

Reputation: 1

I head the same problem.

I set ALLOWED_HOSTS = ["*"] now it works.

Upvotes: 0

nafiseh maraghi
nafiseh maraghi

Reputation: 13

I had to use "OriginValidator" instaed of "AllowedHostsOriginValidator" and set a list of valid domains. here

Upvotes: 1

usama Shehab
usama Shehab

Reputation: 29

i don't know if it will differ but try to make your channel_layers config to be

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

Upvotes: 0

Related Questions