Skip to content

Instantly share code, notes, and snippets.

@taurenk
Last active July 13, 2017 16:22
Show Gist options
  • Save taurenk/3f6e83fc54e7e324a6a4df9cf9934f04 to your computer and use it in GitHub Desktop.
Save taurenk/3f6e83fc54e7e324a6a4df9cf9934f04 to your computer and use it in GitHub Desktop.
Simple Node Web Socket Authentication
/******************/
/** Server Code **/
const WebSocket = require('ws');
const apiKey = 'secret-key';
// https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver
let verifyClient = (info, cb) => {
let submittedApiKey = info.req.headers.apikey;
if (!submittedApiKey) {
console.log('Client tyring to connect without an API key. 401');
cb(false, 401, 'Unauthorized');
} else if (submittedApiKey === apiKey) {
console.log('Authorized client with correct API key.');
cb(true);
} else {
console.log('Client connecting with wrong API key.');
cb(false, 401, 'Unauthorized');
}
}
// ws server accepects a verifyClient function for auth
const wss = new WebSocket.Server({
port: 1337,
verifyClient
});
console.log('WS Server listening on port 1337...');
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
/******************/
/** Client Code **/
const WebSocket = require('ws');
const wsConn = new WebSocket('ws://localhost:1337', {
headers : {
apiKey: 'secret-key-x'
}
});
wsConn.on('open', ()=> {
wsConn.send('Message 1');
});
wsConn.on('message', (data)=> {
console.log(`Recieved message from server: ${data}`);
});
wsConn.on('error', (data)=> {
console.log(`Recieved error from server: ${data}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment