为什么Django Channels不能连接到安全的WebSocket wss?

6
最近我开发了一个叫做“别当个烂朋友”(DBSF)的应用程序,它有点像Facebook,但它会提醒你时不时与你的朋友互动一下。
我遇到了一个很长时间都无法解决的bug。在我的本地机器上应用程序运行正常,但是当我尝试将应用程序部署到Heroku上时,遇到了一个bug。
问题出在用户之间使用WebSockets和Django-channels聊天功能。这是由于Heroku要求https,因此WebSockets也必须是安全的(wss://而不是ws://)引起的。
所以我创建了一个安全的WebSocket,URL以wss://开头。这时候出现了bug:连接从未建立,原因在于asgi.py文件或routing.py文件无法将WebSocket连接到consumers.py中的正确消费者。
以下是我尝试解决此错误的方法:
1.在asgi.py中,我将http更改为https,将websocket更改为其中之一(Websockets、ws、wss)。 2.在settings.py中更改安全设置。 3.尝试不同组合的WebSocket URL。 4.使用Daphne而不是Django的开发服务器来运行它。
没有任何一项解决了这个bug,甚至没有改变错误消息。错误消息总是抱怨套接字仍在连接或已经关闭或处于关闭状态。
以下是一些代码:
在浏览器中(为了在我的本地机器上重新创建bug,我只需硬编码“wss”):
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
      const chatSocket = new WebSocket(
        ws_scheme
        + '://'
        + window.location.host
        + '/ws/chat/'
        + friendship_id
        + '/'
      );

这是 asgi.py 文件

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DBSF.settings")

import django
django.setup()

from django.core.management import call_command


from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            social.routing.websocket_urlpatterns
        )
    ),
})

这是routing.py文件:

from django.urls import re_path, path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),
    
]

以下是consumers.py:

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .models import Message, Friendship, User
import datetime

class ChatConsumer(WebsocketConsumer):
   
    def connect(self):
        print('fuuuuuuuu')
        self.room_name = self.scope['url_route']['kwargs']['friendship_id']
        self.room_group_name = 'chat_%s' % self.room_name
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        sender = text_data_json['sender']
        receiver = text_data_json['receiver']
        friendship_id = self.scope['url_route']['kwargs']['friendship_id']
        message_to_save = Message(conversation=Friendship.objects.get(id=friendship_id), sender=User.objects.get(username=sender), receiver=User.objects.get(username=receiver), text=message, date_sent=datetime.datetime.now())
        message_to_save.save()

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'sender': sender,
                'receiver': receiver,
                'id': message_to_save.id
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        sender = event['sender']
        receiver = event['receiver']
        id = event['id']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message,
            'sender': sender,
            'receiver': receiver,
            'id': id,
        }))

以下是settings.py文件:

"""
Django settings for DBSF project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_HSTS_SECONDS = 3600
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
# Application definition

INSTALLED_APPS = [
    'channels',
    'social',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DBSF.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('https://desolate-lowlands-74512.herokuapp.com/', 6379)],
        },
    },
}

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
        'TIME_ZONE': 'EST'
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'EST'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"



以下是错误信息:

layout.js:108 WebSocket connection to 'wss://desolate-lowlands-74512.herokuapp.com/ws/chat/19/' failed: Error during WebSocket handshake: Unexpected response code: 500

这是完整的项目: https://github.com/fabianomobono/DBSF 这是Heroku上的应用: https://desolate-lowlands-74512.herokuapp.com/ 基本上,asgi.py、routing.py或consumers.py文件中的任意一个都无法使用wss WebSockets。
当我在本地机器上使用普通WebSocket(ws)时,该应用程序可以正常工作。
我真的认为这应该是一个很容易解决的问题,但我已经尝试了几个星期了。
这是一个小错误还是我处理此问题的方法完全错误?
这可能是django-channels的一个错误吗?
请告诉我是否能够帮助我解决这个问题,或者如果您知道之前有人遇到过此问题,请指导我方向。
请告诉我是否足够清楚地解释了这个问题,或者我所问的内容是否不清楚。
有人知道如何解决这个问题吗?

你可以尝试在运行时将它从"127.0.0.1"改为"0.0.0.0"。我使用Flask Socket IO时遇到了问题。https://dev59.com/-K3la4cB1Zd3GeqPR8J0 可以试一下。 - Peter Mølgaard Pallesen
你的意思是使用runserver命令吗? 执行python manage.py runserver 0.0.0.0命令好像没有生效。 - Fabian Omobono
在允许的主机中,您有“127.0.0.1”,也许尝试替换为“0.0.0.0”。 - Peter Mølgaard Pallesen
嗯,没有运气。已将其添加到允许的主机列表中,但是Python manage.py runsenserver仍然连接到127.0.0.1。 - Fabian Omobono
当我运行 python manage.py runserver 0.0.0.0:8000 时,出现了错误... - Fabian Omobono
我遇到了同样的问题。我希望前端能够打开一个wss连接到后端,但它从未建立。这是我的asgi。它对ws连接很好用,但我不确定需要更改什么才能使后端支持wss连接。应用程序=ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) - Neo
1个回答

3

我通过一些改变成功连接到了本地主机。在这些改变之前,即使是ws://协议也无法使用。所以我的更改如下:

  1. 您确定已正确设置了Redis吗?为了测试,您可以尝试
CHANNEL_LAYERS = {
    'default': {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    },
}

在 Github 上的代码中,您的路由出现了错误,应该是:
   re_path(r'wss/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),

但它应该是这样的

    re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),

根据你的 JavaScript 代码。

祝你好运,希望它能有所帮助。


谢谢Anton!这对测试和Heroku非常有用,但我在通道文档中读到不要在生产环境中使用InMemoryChannelLayer。那我在生产环境中应该使用什么??? - Fabian Omobono
1
你需要在Heroku上启用Redis,并获取连接字符串,然后将其放入settings.py中。 - Anton Pomieshchenko
1
没关系!我自己解决了!CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": *** 将heroku-redis URI与端口号一起输入 }, }, }没有第二个参数的端口=>根本没有第二个参数我希望这能为某些人节省很多时间!谢谢Anton!你是超级英雄...如果我们在现实生活中见面,我一定要请你喝啤酒。 - Fabian Omobono
1
谢谢你。也许有一天我们可以喝啤酒,祝你好运。 - Anton Pomieshchenko
@FabianOmobono,我仍然遇到404错误,但是您的答案给了我希望,我很接近了。您能否更详细地描述一下如何设置CHANNEL_LAYERS?这是我的设置方式:CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_TLS_URL', 'redis://localhost:6379')], }, }, } - Dylan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接