Send custom data along with handshakeData in socket.io?

前端 未结 7 1269
迷失自我
迷失自我 2020-11-28 02:18

So I have an application running node js with socket.io as a backend and normal javascript as frontend. My application has a login system which currently simply has the clie

7条回答
  •  温柔的废话
    2020-11-28 02:38

    Old thread but assuming you store your jwt token/session id in session cookies (standard stuff) this gets passed to the server by default anyway when doing handshake (socket.io-client) I've noticed. Is there anything wrong with just getting the auth information for the handshake (via middleware or on.connection) via cookie? eg.

    io.on('connection', function(socket) {
      // assuming base64url token
      const cookieStr = socket.handshake.headers.cookie
      const matchRes =
        cookieStr == null
          ? false
          : cookieStr.match(/my-auth-token=([a-zA-Z0-9_.-]+)/)
      if (matchRes) {
        // verify your jwt...
        if ( tokenIsGood(matchRes[1]) {
          // handle authenticated new socket
        } else {
          socket.emit('AUTH_ERR_LOGOUT')
          socket.disconnect()
        }
      } else {
        socket.emit('AUTH_ERR_LOGOUT')
        socket.disconnect()
      }
    }
    

    I'm using this now for a project and it's working fine.

提交回复
热议问题