Can't add handshake parameter when authenticating socket.io

139 Views Asked by At

I'm using socket.io V1.2.1 & trying to follow the official Socket.io authorization wiki page, but it seems it is a little bit outdated (may be written for version 0.9), so after making a few changes, here is my code for starting my server & configuring the authentication:

server = http.createServer(app)
io = require('socket.io')(server)
global.io = io
global.liveTopicIo = io.of "/live-topic"
server.listen(3100)
io.set 'authorization', (handshakeData, callback)->
    # doing some authentication logic here 
    # & reading 'currentUser'
    if isAuthenticated
        handshakeData.user = currentUser
        callback null, true
    else
        callback null, false

liveTopicIo.on "connection", (socket) ->
  console.log 'user: ', socket.handshake.user
  console.log 'a user connected'

the previous code prints the following

user: undefined

a user connected

So, why I can't add parameters to the handshake data? & how to fix this to add current user?

1

There are 1 best solutions below

0
On BEST ANSWER

Based on the migration notes from 0.9 to 1.x, authorization shouldn't depend on the set function anymore, but instead should be a normal express middleware, so it should be like this:

liveTopicIo.use (socket, next)->
    # doing some authentication logic here based on the info 
    # from socket.handshake & reading 'currentUser'
    if isAuthenticated
        socket.handshake.user = currentUser
        next()
    else
        next(new Error("Access Denied"))