【问题标题】:Can't add handshake parameter when authenticating socket.io验证socket.io时无法添加握手参数
【发布时间】:2015-02-12 16:58:52
【问题描述】:

我正在使用 socket.io V1.2.1 并尝试关注official Socket.io authorization wiki page,但它似乎有点过时(可能是为 0.9 版编写的),所以在进行了一些更改之后,这是我的用于启动我的服务器和配置身份验证的代码:

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'

前面的代码打印以下内容

用户:未定义

连接的用户

那么,为什么我不能向handshake 数据添加参数?以及如何解决此问题以添加当前用户?

【问题讨论】:

    标签: node.js express socket.io socket.io-1.0


    【解决方案1】:

    基于the migration notes from 0.9 to 1.x,授权不应该再依赖set函数,而应该是一个普通的express中间件,所以应该是这样的:

    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"))
    

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2011-09-27
      • 2018-07-15
      • 2017-02-17
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多