Securing Socket.io

后端 未结 3 1099
臣服心动
臣服心动 2020-12-15 21:03

I am using a Node.js based https server that authenticates using HTTP Basic (which is fine as the data are sent over the SSL encrypted connection).

Now I want to pro

相关标签:
3条回答
  • 2020-12-15 21:41

    Although the answer by Linus is basically right, I now solved it in a more easy way using the session.socket.io - which basically does the same thing, but with way less custom-code to write.

    0 讨论(0)
  • 2020-12-15 21:47

    Edit: Of course OP is right in their other answer; what's more, with socket.io >1.0 you might use socket.io-express-session.

    Original answer:

    Socket.io supports authorization via the io.set('authorization', callback) mechanism. See the relevant documentation: Authorizing. Here's a simple example (this authenticates using a cookie-based session, and a connect/express session store -- if you need something else, you just implement another 'authorization' handler):

    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);
            });
        });
    });
    
    0 讨论(0)
  • 2020-12-15 21:57
    1. Setting the socket to be secured is done by:

      • setting the secure flag - as you wrote ({secure: true})
      • OR by using https protocol when creating the server (instead of http) - which will set the secure flag to be true automatically
    2. Good lib that simplify the authentication process is: https://github.com/auth0/socketio-jwt

    0 讨论(0)
提交回复
热议问题