Joenel de Asis Joenel de Asis - 3 months ago 11
Javascript Question

Authorizing and handshaking with Socket.IO

I'm wondering what the main function of authorization and the handshake in Socket.IO is. I've already read their wiki and authorizing guide on GitHub but I still don't understand the following:


  1. How does the authorization work in Socket.io?

  2. What is the handshake in Socket.IO?

  3. Can I add anything to the
    handshakeData
    object?



I hope you can answer my question. Thanks.

Answer

Edit: In Socket.IO 1.0, middleware is now used. Authorization can be done like so:

io.use(function(socket, next) {
  var handshake = socket.request;
  next();
});

If you were to need to reject the socket, just pass an error object to the next() callback. The same thing can be done with namespaces:

io.of('/namespace').use(function(socket, next) {
  var handshake = socket.request;
  next();
});

Authorization in Socket.IO is run through a function which is decided in a boolean that is passed by a callback. This function runs every time a connection attempts a handshake, and this is what it looks like:

io.set('authorization', function (handshake, callback) {
  callback(null, true);
});

The function callback() accepts two parameters. The first is the error reason, if any, and the second parameter is the boolean that decides if a client may connect or not. By default there is no authorization, so the scenario is shown in the code sample above, where the socket that is connecting is allowed passage with true.

The handshake in Socket.IO is like any other information technology related handshake. It is the process of negotiation, which in Socket.IO's case, decides whether a client may connect, and if not, denies the connection. The handshake is initiated with either a XHR or JSONP request, and doesn't do much when no authorization is specified, but can be helpful in the data passed in the handshake data object.

To answer your last question, yes, you may add anything into the handshake object. The object is the same variable reference to the socket.handshake object, which allows you to do things like this:

io.set('authorization', function (handshake, callback) {
  handshake.foo = 'bar';
  callback(null, true);
});

io.sockets.on('connection', function(socket) {
  console.log(socket.handshake.foo); // bar
});

This is very useful, because you can store socket-based properties. A common use for this is with the Express framework, where one can identify the session ID based on the cookies passed by Socket.IO, which then a matching session can be identified.

Comments