1

I have the following code:

io.sockets.on('connection', function (socket) {

    socket.on('queue', function() {
        console.log(socket.request.headers.cookie);

    })
});

Now registration to my website is done by express and an https cookie is added to the client's browser by express. When someone wants to connect to my, let's say game he needs to emit a "queue event". there, socket.io will read his cookies and check if they are correct.

According to this thread: Can I access a cookie from Socket.io?

socket.request.headers.cookie

headers.cookie is a no-no, even though I don't really understand why. why would socket.io confuse his cookie with someone else's in real time production? what am I missing? how can I make this right?

user1938653
  • 611
  • 1
  • 9
  • 21

1 Answers1

0

If you want some authentication with Socket.io, best way to do it is by using handshakes.

Let's say you're already authentified and the server sent you back a token

Client side :

let socket = io.connect(SERVER.socket, { query: 'token=' + token })
         .on('connect', data => {
             console.log('Connected to the server');
         };

Server side is running a middleware on socket connection :

const io = require('socket.io').listen(httpServer)

// Checking for the token and handshaking with the client
.use(require('socketio-jwt').authorize({
    secret: secretKey,
    handshake: true
}))

// Client successfully connected (token was valid)
.on('connection', socket => {});

Some good tutorials about that : https://auth0.com/blog/auth-with-socket-io/

Hope it'll help you in some way.

Alexis Facques
  • 1,783
  • 11
  • 19
  • Any clue about the "client.request.headers.cookie leads to race conditions as the cookie always points to the last logged in user." message? – user1938653 Jun 28 '17 at 16:59