Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Last active September 19, 2023 23:38
Show Gist options
  • Save jfromaniello/8418116 to your computer and use it in GitHub Desktop.
Save jfromaniello/8418116 to your computer and use it in GitHub Desktop.
Example of authenticating websockets with JWTs.
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 8080});
var jwt = require('jsonwebtoken');
/**
The way I like to work with 'ws' is to convert everything to an event if possible.
**/
function toEvent (message) {
try {
var event = JSON.parse(message);
this.emit(event.type, event.payload);
} catch(err) {
console.log('not an event' , err);
}
}
wss.on('connection', function(ws) {
ws.on('message', toEvent)
.on('authenticate', function (data) {
jwt.verify(data.token, options, function (err, decoded) {
//now is authenticated
});
});
ws.send('something');
});
@ShejaEddy
Copy link

ShejaEddy commented Apr 24, 2020

that code snippet has a lot of vulnerabilities:

  • you must check time of life of the token
  • you must check currently received user agent data with the same data, that you placed in token previously
  • you must store additional refresh token for auth token refreshing
  • you must minimize jwt.verify() operations (store token in special registry, in redis for example)
  • etc

@msafronov, My question can be somehow silly but I was asking myself why do we have to store tokens from the client, why not authenticate his tokens each time he reconnects to the sockets, then we could reset ws.userId at each authentication. Save authenticated users in a static object like a client room or something after each authentication. So I don't get the point of why saving the token.

@OBorce
Copy link

OBorce commented Jul 15, 2020

@ShejaEddy probably something like the token can expire and the client can keep the connection open forever?

@ShejaEddy
Copy link

@OBorce u get my point, that's why what I do is only save the userId as key to users object then save the token as it's value. so that every time the user's token changes u'll know which token to update due to the saved userId.

@arashmad
Copy link

arashmad commented Dec 4, 2020

Is there any option to connect to a WebSocket through username and password authentication?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment