-
-
Save jfromaniello/8418116 to your computer and use it in GitHub Desktop.
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'); | |
}); | |
This works for me:
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var msg = {
type: 'authenticate',
payload: { token: 'XXX' }
};
ws.onopen = function(event) {
ws.send(JSON.stringify(msg));
};
Something to keep in mind: non-authenticated clients should not receive broadcasts. So when broadcasting you have to perform an additional check (or filter).
wss.broadcastAll = function broadcastAll(data) {
wss.clients.forEach(client => {
client.send(data);
});
};
wss.broadcastAuth= function broadcastAuth(data) {
wss.clients.forEach(client => {
// Check if the socket is authenticated here
client.send(data);
});
};
(or you can maintain a separate client list for authenticated client, etc.)
@Nepoxx or you can just join the authenticated users in a dedicated room and broadcast a mesage to authenticated room only for authenticated users
@jfromaniello Thank you for this - I like the emit toEvent.
After jwt.verify do you do something like
wss.on('connection', function(ws) {
ws.on('message', toEvent)
.on('authenticate', function (data) {
jwt.verify(data.token, options, function (err, decoded) {
ws.userId=...
//now is authenticated
});
.on('updateAccount',function(data){
if(ws.userId){
//user previously authenticated - update
}
}
});
ws.send('something');
});
@andreigiura I think you're thinking of https://github.com/socketio/socket.io. This example is based on the simpler https://github.com/websockets/ws.
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
The toEvent
approach is indeed cool. Some notes. The error message "not an event" is wrong. It should be "not an object" there. I'd suggest the following version, which allows us to process any data including strings. Assuming the payload is neither 0
or undefined
it allows to handle the objects with wrong structure too:
function toEvent (message) {
try {
let {type, payload} = JSON.parse(message)
this.emit(type, payload || message)
} catch (ignore) {
this.emit(undefined, message)
}
}
This way any data other then event objects can be processed too:
ws.on('undefined', message => console.log(message))
Finally, you may need to check the type
for reserved words, e.g. the message
, and avoid using them.
@kotoo great points. I've understood all of them, except for you must check currently received user agent data with the same data, that you placed in token previously. Could you explain a bit more and the thought process behind what this means. I thought we should be storing only the token. Do we need to store the user agent, req headers, etc.. too. Also you mentioned reducing jwt.verify() calls which I understand even though is asynchronous has to at some point perform it and is a definite bottleneck. But is it too costly. Doesn't jwt store al of it's token in memory. If not, then storing it in redis makes sense. Thank you!
@kanalasumant I think the idea behind the user agent check is to help ensure that the websocket connection originates from the same source as the initial login. A single user can have multiple tokens (say token A for web, and token B for mobile). Let's say the user logs in the web app and is given token A. The request for token A also provided user agent info A. Now the web app uses token A to make the websocket connection. That websocket request will have the same user-agent info A in the headers and will help ensure that both requests originate from the same source application. This information can easily be spoofed but it would require an attacker to have access to the user agent info or try a bunch of user agents until a match occurs. You could possibly take action when a mismatch occurs (revoke or maybe after N mismatches lockout the user, or block login attempts from mismatch's IP+user combo) . These are my initial thoughts and I haven't implemented this but it will be on my todo list.
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.
@ShejaEddy probably something like the token can expire and the client can keep the connection open forever?
@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.
Is there any option to connect to a WebSocket through username and password authentication?
Do you have sample code for client side? I am not sure how to invoke 'authenticate' event on server..