我正在嘗試構建一個vue.js用作前端和django后端的聊天網站。它作業正常,Firefox但在MS edge和 中Google Chrome,Websocket 失敗了。我在瀏覽器控制臺中收到此訊息。
WebSocket connection to 'ws://127.0.0.1:8000/inbox/' failed
我django-channels在 python 控制臺中使用它列印
WebSocket CONNECT /inbox/ [127.0.0.1:4965]
WebSocket DISCONNECT /inbox/ [127.0.0.1:4965]
當我列印出錯誤代碼時,我得到 1006
關閉代碼 1006 是一個特殊代碼,表示瀏覽器實作例外(本地)關閉了連接。
我的 WebSocket 代碼
new WebSocket(url, authToken) // I use sec-websocket-protocol to transfer the authentication token
我做錯了什么還是瀏覽器有問題?
- 更新
new WebSocket("ws://127.0.0.1:8000/inbox/", "authtoken");
因此,我在第二個 Websocket 協議中發送身份驗證令牌,并使用中間件在后端對用戶進行身份驗證。當我洗掉該協議并在后端接受未經身份驗證的用戶時 ->
new WebSocket("ws://127.0.0.1:8000/inbox/");
-> WebSocket 連接正常。問題是在發送第二個 Websocket 協議時。
uj5u.com熱心網友回復:
我將“令牌”作為子協議添加到 WebSocket 和 authToken 中。然后在后端,我用相同的子協議名稱接受了它:
我的網路套接字
new WebSocket(url, ["Token", authToken]) // Sending 'Token' and authToken as subprotocols
令牌認證中間件
from asgiref.sync import sync_to_async
from django.contrib.auth.models import AnonymousUser
from rest_framework.authtoken.models import Token
@sync_to_async
def get_user(headers):
try:
token_key = headers[b"sec-websocket-protocol"].decode().split(', ')[1]
token = Token.objects.get(key=token_key)
return token.user
except Token.DoesNotExist:
return AnonymousUser()
class TokenAuthMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
headers = dict(scope["headers"])
if b"sec-websocket-protocol" in headers:
scope['user'] = await get_user(headers)
return await self.app(scope, receive, send)
消費者.py
from channels.generic.websocket import AsyncWebsocketConsumer
class Consumer(AsyncWebsocketConsumer):
async def connect(self):
self.user = self.scope['user']
if self.user.is_authenticated:
self.room_name = await self.get_user_id(self.user)
self.room_group_name = self.room_name
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept('Token') # Here I'm giving a subprotocol to the self.accept function
else:
await self.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/379682.html
標籤:谷歌浏览器 网络套接字 microsoft-edge Django频道
上一篇:為什么對端接聽后會自動播放音頻?
