Node.js + socket.io + mongo with authorization

On my website users need to login with database account. My question is, how to auth socket.io only if database login pass and create my variable in cookie ?

Express with auth function from here socket.io Auth works with sessionID, maybe i can prevent to give sessionID to moment when user log in to database ?

Use the authorization function:

io.set('authorization', function (handshakeData, callback) {
  // findDatabyip is an async example function
  findDatabyIP(handshakeData.address.address, function (err, data) {
    if (err) return callback(err);

    if (data.authorized) {
      handshakeData.foo = 'bar';
      for(var prop in data) handshakeData[prop] = data[prop];
      callback(null, true);
    } else {
      callback(null, false);
    }
  }) 
});
  • Replace findDatabyIP with your database lookup.
  • Any attributes you set on handshakeData should be available in your "connection" handler via socket.handshake.sessionID.
  • Call callback when you're done, with an error message (if applicable), and true if the connection is authorized, false if it's not.
  • Parsing and reading the session's cookie may be difficult. This discussion (especially jugglinmike's post) may help.