Skip to content
Arnout Kazemier edited this page Jul 2, 2011 · 32 revisions

Authorization

Socket.IO has support has for 2 different authorization methods. Authorization can be applied globally which will be done during the initialization / handshaking process or it can be done per namespace.

Global authorization can be used together together or independent from each other. The only thing they have in common is the handshakeData object. The data object is generated with the request data from the handshake. So to have a better understanding of how to work with authorization you first need to understand the handshaking process.

Handshaking

When a client wants to establish a persistent real time connection with the Socket.IO server it needs to start a handshaking processing. The handshake is initiated with either a XHR request or JSONP request (for cross domain requests).

When the server receives a connection it will start gathering data from the request that might be needed later this is done for two reasons:

  1. Users might want authorize the clients based on information from the headers or IP address.
  2. Not all transports sends headers when they attempt to establish a real time connection with the server, so we store the handshake data internally so we are sure users can re-use this data again for when the client is connect. For example you might want to read out the session id from the cookie headers and initialize the Express session for the connected socket.

The handshakeData object contains the following information:

{
 , headers: req.headers      // the headers that where send with this request
 , time: (new Date) +''      // date time of the connection
 , address: socket.address() // location and port object
 , xdomain: !!headers.origin // was it a cross domain request
 , secure: socket.secure     // https connection?
}

The address is the result of socket.address()

After we stored all information we check if a global authorization function has been configured. If this is the case we pass it in authorization function the handshakeData object and a callback function. When the callback is called, we decide if we need return connection details or deny it.

#Global authorization Global authorization is enabled by setting the authorization configuration method.

io.configure(function (){
  io.set('authorization', function (handshakeData, callback) {
    callback(null, true); // error first callback style 
  });
});

In side the authorization function above you receive 2 arguments

  1. handshakeData, the handshakeData object that we generated during handshaking
  2. callback, as handshakes might require database look-ups. It requires 2 arguments, error which can be undefined or a String in case of the error and authorized a Boolean indicating if the client is authorized.

Sending an error or setting the authorized argument to false both result in not allowing the client to connect to the server.

Clone this wiki locally