1

我是用于 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);

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

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

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

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

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

感激地收到任何帮助

4

2 回答 2

0

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

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
于 2020-10-08T11:02:11.493 回答
-1

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

于 2020-10-04T08:55:18.680 回答