Skip to content

Instantly share code, notes, and snippets.

@wlkns
Last active January 1, 2016 09:09
Show Gist options
  • Save wlkns/8123515 to your computer and use it in GitHub Desktop.
Save wlkns/8123515 to your computer and use it in GitHub Desktop.
Socket.IO Authentication Tutorial (Server and Client) - http://wlkns.co/?p=52
/* app.js
*
* This code is the client to connect to the Socket.IO server run in the clients browser */
jQuery(document).ready(function(){
/* Connect the socket */
socket = io.connect('http://localhost:8080', {
/* Pass the authentication token as a URL parameter */
query: $.param({token: 'i271az2Z0PMjhd6w0rX019g0iS7c2q4R'})
/* My application is more complicated, so I use jQuery's .param utility to convert the Object to an URL string e.g. 'token=abc&etc=cde' */
});
console.log("Connecting...");
/* Bind all the most common events for debugging... we use "message" in server.js, so I put that first */
var events = ['message', 'connect', 'connecting', 'disconnect', 'connect_failed', 'connect_timeout', 'connect_error', 'error', 'reconnect_failed', 'reconnect', 'reconnecting', 'disconnect'];
for ( var i in events )
{
event_name = events[i];
/* Output the event and any data to the browser console */
socket.on(event_name, function( data ) {
console.log(event_name, data);
});
}
});
// server.js
// The Node JS Socket.IO Server
// Launch the server, I've used express as most people use Socket.IO on Express
var app = require('express').createServer(),
io = require('socket.io').listen(app);
server.listen(8080);
// We will use token based authentication, these could be session ID's or username/passwords...
var tokens = [
'i271az2Z0PMjhd6w0rX019g0iS7c2q4R',
'oWD4sh1eU2Yhn95C05t2YKrKMVWoAFAk'
];
// Socket.IO Connections first get passed through Authorization (if it exists)
io.set('authorization', function(req, callback) {
// Some basic validation to make sure a token was passed
if ( req.query.token === undefined || req.query.token.length === 0 )
{
return false;
}
// Loop through the valid tokens, to validate the token passed
var validated = false;
for ( var key in tokens )
{
if ( key == req.query.token )
{
validated = true;
break;
}
}
// If valid, continue to callback the next function
if ( validated )
{
return callback(null, true);
}
else
{
return false;
}
});
// Everything else Socket.IO works normally...
io.sockets.on('connection', function (socket) {
console.log('Client connected from: ' + socket.handshake.address);
// Send the server date every 30 seconds, just to validate the connection
setInterval(function(){
io.sockets.emit('message', (new Date()));
}, 30000);
socket.on('disconnect', function () {
console.log('Client disconnected.');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment