You can either save sessions in Memcached or Redis. You can then retrieve session data from one of these repositories.
Both memcache and redis packages are available for nodejs.
Also note that you can use middleware for authentication in socket.io. Then you do not need to insert authentication logic into the connection event handler.
var authorization = require('./socket/authorization')(app); io.use(authorization.authorize);
And as an example of this memcached auth file, which in our case reads a cookie stored on our php.
var memcached = require('memcached'), cookie = require('cookie), debug = require('debug')('socket.io:authorization'); module.exports = function(app) { var authorize = function(socket, next) { var handshakeData = socket.request; if (handshakeData.headers.cookie) { handshakeData.cookie = cookie.parse(handshakeData.headers.cookie); if (typeof handshakeData.cookie['node'] === 'undefined') { next(new Error('No cookie transmitted.')); } else { var loginEndIndex = handshakeData.cookie['node'].indexOf(','); handshakeData.node = handshakeData.cookie['node'].slice(0, loginEndIndex); var memcached = new Memcached(app.config.memcached.server, app.config.memcached.options); memcached.on('failure', function(details) { debug('Server: %s went down due to %s', details.server, details.messages.join(' ')); }); memcached.on('reconnecting', function(details) { debug('Total downtime caused by server %s: %sms', details.server, details.totalDownTime); }); memcached.get(handshakeData.cookie['PHPSESSID'], function(err, result) { if (!err && result !== false) { var pipeIndex = result.indexOf('|'), phpData = result.slice(pipeIndex + 1), obj = php.unserialize(phpData); if (handshakeData.node === obj.userLogin) { debug('coockie-accepted: %s, %s', handshakeData.node, obj.userLogin); next(); } else { debug('cookie-revoked; %s, %s', handshakeData.node, obj.userLogin); next(new Error('Cookie is invalid.')); } } else { debug('error: %s', err); next(new Error('Cookie is invalid.')); } memcached.end(); }); } } else { debug('error: No cookie transmitted.'); next(new Error('No cookie transmitted.')); } }; return { authorize: authorize }; };
source share