【问题标题】:How to access user object using passportSocketIo如何使用 passportSocketIo 访问用户对象
【发布时间】:2021-01-18 19:30:13
【问题描述】:

我是用于 express 和 socket.io 服务器身份验证的用户 passport.js。我已经通过使用 passportSocketIo 来解决这个问题。当经过身份验证的用户访问服务器时,他们会成功反序列化并成功回调。

但是,我现在想访问反序列化的用户详细信息并将它们附加到套接字以用于核心服务器功能。谁能告诉我在哪里可以找到这些详细信息?

对于上下文,实现如下所示...

 passportSocketIo.authorize({
      cookieParser: cookieParser,       // the same middleware you registrer in express
      key:          'auth',       // the name of the cookie where express/connect stores its session_id
      secret:       'keyboard cat',    // the session_secret to parse the cookie
      store:        tediousConfig,        // we NEED to use a sessionstore. no memorystore please
      success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
      fail:         onAuthorizeFail,     // *optional* callback on fail/error - read more below
    })(socket, next);

成功功能是基本的。我可以在此处的数据参数中找到反序列化的用户,但在这里我无法访问套接字以将这些详细信息永久附加到。

function onAuthorizeSuccess(data, accept){
  const userId = data.user.id
  console.log(`User connected: ${userId}`)
  accept()
}

此函数运行良好,我可以在成功函数中访问用户 ID(如 console.log 中所示)。

一种解决方案可能是将套接字也传递给成功函数并在此处附加详细信息,但我不明白“数据”和“接受”参数的来源足够好以便能够传递这些在。

对于我正在尝试做的事情,很可能还有一个更简单的解决方案!

感谢您的帮助

【问题讨论】:

    标签: node.js socket.io passport.js passport.socketio


    【解决方案1】:

    如果其他人遇到这个问题,我只是在稍后的 io.use 中间件中附加用户访问了套接字。

    【讨论】:

      【解决方案2】:

      您可以使用以下方式访问您的用户对象,该对象已为您添加了护照:-

      socket.request.user
      

      这是文档的链接: https://github.com/jfromaniello/passport.socketio#socketrequestuser-as-of-v1

      这是确切的文档,以防文档发生任何更改

      socket.handshake.user (prior to v1)
      This property was removed in v1. See socket.request.user
      
      socket.request.user (as of v1)
      This property is always available from inside a io.on('connection') handler. If the user is authorized via passport, you can access all the properties from there. Plus you have the socket.request.user.logged_in property which tells you whether the user is currently authorized or not.
      
      Note: This property was named socket.handshake.user prior to v1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2022-12-12
        • 2020-02-13
        • 2018-10-02
        • 1970-01-01
        相关资源
        最近更新 更多