Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  22] [ 2]  / answers: 1 / hits: 47311  / 11 Years ago, tue, october 1, 2013, 12:00:00

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.


More From » node.js

 Answers
158

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.


[#75318] Monday, September 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;