我找到了解决方案。如我错了请纠正我。
建立Web套接字连接后,将令牌发送到服务器。在接收方法的服务器(在我的情况下是django频道)中,我获取该令牌,如果令牌有效,我更新连接信息,如果令牌无效,则断开连接。
这样的事情:
js文件:
const socket = new WebSocket('ws://localhost:8001/announcement'); socket.onopen = function open() { console.log('WebSockets connection created.'); let authData = {'token': '<valid-token-here>'} socket.send(JSON.stringify(authData)); };
在服务器端(例如django):
def receive(self, text_data=None, bytes_data=None): if self.scope['user'].id: pass else: try: # It means user is not authenticated yet. data = json.loads(text_data) if 'token' in data.keys(): token = data['token'] user = fetch_user_from_token(token) self.scope['user'] = user except Exception as e: # Data is not valid, so close it. print(e) pass if not self.scope['user'].id: self.close()