I am using a Node.js based https server that authenticates using HTTP Basic (which is fine as the data are sent over the SSL encrypted connection).
Now I want to pro
Although the answer by Linus is basically right, I now solved it in a more easy way using the session.socket.io - which basically does the same thing, but with way less custom-code to write.
Edit: Of course OP is right in their other answer; what's more, with socket.io >1.0 you might use socket.io-express-session.
Original answer:
Socket.io supports authorization via the io.set('authorization', callback)
mechanism. See the relevant documentation: Authorizing. Here's a simple example (this authenticates using a cookie-based session, and a connect/express session store -- if you need something else, you just implement another 'authorization' handler):
var utils = require('connect').utils;
// Set up a session store of some kind
var sessionId = 'some id';
var sessionStore = new MemoryStore();
// Make express app use the session store
app.use(express.session({store: sessionStore, key: sessionId});
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
var cookie = utils.parseCookie(handshakeData.headers.cookie);
if(!(sessionId in cookie)) {
return callback(null, false);
}
sessionStore.get(cookie[sessionId], function (err, session) {
if(err) {
return callback(err);
}
if(!('user' in session)) {
return callback(null, false);
}
// This is an authenticated user!
// Store the session on handshakeData, it will be available in connection handler
handshakeData.session = session;
callback(null, true);
});
});
});
Setting the socket to be secured is done by:
Good lib that simplify the authentication process is: https://github.com/auth0/socketio-jwt