How to access session identifier when using Socket.IO?

前端 未结 1 1718
抹茶落季
抹茶落季 2021-02-06 08:21

I have a chat, and I need to manage unique connections. I searched around, but the solutions that I have found all appear to be deprecated.

So, how would I get a socket\

相关标签:
1条回答
  • 2021-02-06 09:06

    Use the Socket.IO authentication setting, and pass the cookies to the cookie parser middleware from Express. Once the cookie is parsed, you can get the session ID of the client, and fetch the associated session from the session store, whether it is a memory story or other type of store.

    // we need to use the same secret for Socket.IO and Express
    var parseCookie = express.cookieParser(secret);
    var store = /* your MemoryStore, RedisStore, etc */;
    
    io.set('authorization', function(handshake, callback) {
      if (handshake.headers.cookie) {
        // pass a req, res, and next as if it were middleware
        parseCookie(handshake, null, function(err) {
          handshake.sessionID = handshake.signedCookies['connect.sid'];
          // or if you don't have signed cookies
          handshake.sessionID = handshake.cookies['connect.sid'];
    
          store.get(handshake.sessionID, function (err, session) {
            if (err || !session) {
              // if we cannot grab a session, turn down the connection
              callback('Session not found.', false);
            } else {
              // save the session data and accept the connection
              handshake.session = session;
              callback(null, true);
            }
          });
        });
      } else {
        return callback('No session.', false);
      }
      callback(null, true);
    });
    

    Each time a client attempts to connect, the authorization function is run. It takes the handshake header cookies (handshake.headers.cookies), and passes them to express.cookieParser(). The cookie parser then finds the session ID, and then searches the store for the associated session. Then, we store the associated session into handshake.session, so we can access it like this:

    app.get('/', function(req, res) {
      req.session.property = 'a value';
    });
    
    io.sockets.on('connection', function(socket) {
      var session = socket.handshake.session;
      session.property // a value
    });
    
    0 讨论(0)
提交回复
热议问题