我在docs的服务器上使用Node v8.6.0。我不会使用Socket.io。
我希望用户通过GET请求发送(即通过自定义标头)JWT,然后被拒绝(他们没有被授权)并阻止建立websocket,或者如果他们发送有效的JWT,我希望将GET请求升级到websocket。
axios.get('http://localhost:3001/upgrade', {
headers: {
Authorization: 'bearer jwtGoesHere',
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Version': 13
}
})
但是,无法发送自定义标头。如果我尝试发送所需的标题以升级到websocket,我会收到错误:Refused to set unsafe header
。环顾网络,我发现在尝试建立websocket连接时,有两种方式可以发送某种信息:this library和this。然而,它们对我来说似乎有些苛刻,或者至少是非标准的解决方案(通过这种方式发送JWT是否可以?)。
目前,这是我的代码在服务器上的样子(使用TypeScript):
const webSockets: any = {};
const webSocketServer: any = new WebSocket.Server({ noServer: true });
server.on('upgrade', (request: any, socket: any, head: any) => {
webSocketServer.handleUpgrade(request, socket, head, (websocket: any) => {
let userID: any;
console.log('establishing websocket connection...');
websocket.send('plz send ID');
websocket.on('message', (message: any): any => {
if (JSON.parse(message).userId) {
userID = JSON.parse(message).userId;
if (!webSockets[userID]) {
console.log('preparing websocket user...');
webSockets[userID] = websocket;
}
console.log(`connected: ${userID}`);
}
});
websocket.on('close', (eventCode: any): any => {
if (eventCode === 1006) {
console.log('Websocket disconnected abnormally');
}
if (eventCode === 1000) {
console.log('Websocket successfully closed normally');
delete webSockets[userID];
console.log(`deleted: ${userID}`);
}
});
});
});
在客户端,我只使用本机WebSocket。