Skip to content

Instantly share code, notes, and snippets.

@stasyanko
Forked from jfromaniello/gist:8418116
Created February 18, 2017 06:20
Show Gist options
  • Save stasyanko/b0d0f80a9e8d07f89a88f7232c7da676 to your computer and use it in GitHub Desktop.
Save stasyanko/b0d0f80a9e8d07f89a88f7232c7da676 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');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment