I'm using Node v8.6.0 on the sever with this library. I will not be using Socket.io.
I would like a user to send (i.e. via a custom header) a JWT through a GET request that will then either get rejected (they aren't authorized) and prevent a websocket from being established, or, in the case they send a valid JWT, I want the GET request to be upgraded to a websocket.
axios.get('http://localhost:3001/upgrade', {
headers: {
Authorization: 'bearer jwtGoesHere',
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Version': 13
}
})
However, there is no way to send custom headers. If I try to send the required headers for upgrading to a websocket, I get an error: Refused to set unsafe header
. Looking around the web, I see there are potentially 2 ways to send in some kind of information through when trying to establish a websocket connection: this and this. However, they seem kind of hacky to me or at least non-standard solutions (would it be okay to send a JWT through this way?).
Currently, this is what my code looks like on the server (with 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}`);
}
});
});
});
And on the client side I'm just using native WebSocket.