Socket.io Protection

I am using the https server Node.js, which performs authentication using HTTP Basic (which is fine, as the data is transmitted over an SSL-encrypted connection).

Now I want to provide a Socket.io connection, which should be

  • encrypted and
  • Only for authenticated users.

The question is how to do this. I already figured out what I need to specify { secure: true }in the client JavaScript code when connecting to the socket, but how can I force socket connections on the server side to be launched only via SSL and that it works only for authentication users?

I think the SSL business is the easy part, as the Socket.io server is only tied to the https server, so it should only work using SSL, and it should not be possible to run it on top of the (optional) running http server, right?

As for the other thing, I have no idea how to ensure that socket connections can only be established after successful authentication of the user using HTTP Basic.

Any ideas?

+5
source share
3 answers

Although Linus' answer is mostly right, I now solved it in a simpler way using session.socket.io - which basically does the same thing, but with much less user code for writing.

+5
source

: , OP ; , socket.io > 1.0 socket.io-express-session.

:

Socket.io io.set('authorization', callback). . : Authorizing. ( cookie connect/express - - , ):

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);
        });
    });
});
+14
+1
source

All Articles