title: Why does django-channels not connect to secure Websockets wss?
body: <p>Lately I have been developing an app called(DBSF - don't be a sh***y friend), which functions a little bit like facebook, but it reminds you to interact with your friends once in a while.
  I've encountered a bug that I have been unable to fix for a long time.</p>
  <p>The app works fine on my local machine but I run into one bug when I try to deploy the app to heroku.</p>
  <p>The issue is about the chat function between users which uses Websockets and Django-channels.
  It is caused by heroku requiring https, therefore the websockets have to be secure as well (wss:// instead of ws://).</p>
  <p>So I did that, I created a secure webSocket with a url that starts with wss://</p>
  <p>And here is where the bug happens: the connection never gets established for some reason the the asgi.py file, or the routing.py file can't connect the websocket to the correct consumer in consumers.py</p>
  <p><strong>Here's how I tried to fix the bug:</strong></p>
  <ol>
  <li>in asgi.py I changed http to https, or websocket to one of these(websockets, ws wss)</li>
  <li>changed security settings in settings.py</li>
  <li>tried different combinations of the websocket url</li>
  <li>running it with daphne instead of Django's development server</li>
  </ol>
  <p>None of these changed the bug or even the error messages.</p>
  <p>The error message always complains that the socket is still connecting or already closing or in closing state</p>
  <p>Here's some code</p>
  <p>on the browser (to recreate the bug on my local machine i just hard code 'wss'):</p>
  <pre class="lang-js prettyprint-override"><code>var ws_scheme = window.location.protocol == &quot;https:&quot; ? &quot;wss&quot; : &quot;ws&quot;;
        const chatSocket = new WebSocket(
          ws_scheme
          + '://'
          + window.location.host
          + '/ws/chat/'
          + friendship_id
          + '/'
        );
  </code></pre>
  <p>here's asgi.py</p>
  <pre class="lang-py prettyprint-override"><code>import os
  os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;DBSF.settings&quot;)
  
  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({
      &quot;http&quot;: get_asgi_application(),
      &quot;websocket&quot;: AuthMiddlewareStack(
          URLRouter(
              social.routing.websocket_urlpatterns
          )
      ),
  })
  </code></pre>
  <p>here's routing.py</p>
  <pre class="lang-py prettyprint-override"><code>from django.urls import re_path, path
  from . import consumers
  
  websocket_urlpatterns = [
      re_path(r'ws/chat/(?P&lt;friendship_id&gt;\w+)/$', consumers.ChatConsumer.as_asgi()),
      
  ]
  </code></pre>
  <p>here's consumers.py</p>
  <pre class="lang-py prettyprint-override"><code>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,
          }))
  </code></pre>
  <p>Here is settings.py:</p>
  <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;
  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/
  &quot;&quot;&quot;
  
  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': {
              &quot;hosts&quot;: [('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= &quot;/media/&quot;
  
  
  
  </code></pre>
  <p>Here is the error message:</p>
  <pre><code>layout.js:108 WebSocket connection to 'wss://desolate-lowlands-74512.herokuapp.com/ws/chat/19/' failed: Error during WebSocket handshake: Unexpected response code: 500
  </code></pre>
  <p>Here is the full project:
  <a href="https://github.com/fabianomobono/DBSF" rel="noreferrer">https://github.com/fabianomobono/DBSF</a></p>
  <p>And here is the app on heroku:
  <a href="https://desolate-lowlands-74512.herokuapp.com/" rel="noreferrer">https://desolate-lowlands-74512.herokuapp.com/</a></p>
  <p>Basically the one of the files asgi.py , routing.py or consumers.py can't work with wss WebSockets.</p>
  <p>The app works when I use a normal webSocket(ws) on my local machine.</p>
  <p>I really thought this would be an easy issue to fix but I have been trying for weeks now.</p>
  <p>Is this a small bug or is the way I am trying to approach this completely wrong?</p>
  <p>Could this be a bug of django-channels??</p>
  <p>Please let me know if you'd be able to help me with this or if you could point me in the direction of someone who faced this problem before.</p>
  <p>Please let me know if I explained this bug well enough or if it is not clear what I am asking.</p>
  <p>Does anybody know how to fix this?</p>