1

我最近在我的快递服务器上实施了 passport.js 以进行身份​​验证。我也在尝试为我的 socket.io 服务器利用此身份验证。所以我正在尝试使用 passport.socketio 包来执行此操作。

我这样使用它:

io.use(async (socket, next) => {
    console.log("pre auth")

    await 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
    })

    console.log("post auth")
}

成功和失败回调是:

function onAuthorizeSuccess(data, accept){
  console.log("Success connection to socket.io");
  accept();
}

function onAuthorizeFail(data, message, error, accept){
  if(error) 
    throw new Error(message);

  console.log("failed connection to web socket", message);
}

但是,当我尝试连接时,我同时收到“pre auth”和“post auth”的控制台消息,但没有来自授权功能的消息,也没有任何错误消息。

任何帮助将不胜感激!

4

1 回答 1

2

namespace.use 方法是一种将中间件(函数)添加到套接字的方法。所以它期待一个功能。另一方面,passportSocketIo.authorize 正在返回中间件函数,您可以在此处查看代码。因此,您有 2 个选项,您可以像在文档中指定的那样使用它:

io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,       // the same middleware you registrer in express
  key:          'express.sid',       // the name of the cookie where express/connect stores its session_id
  secret:       'session_secret',    // the session_secret to parse the cookie
  store:        sessionStore,        // 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
}));

或者你像这样自定义它:

io.use(async (socket, next) => {
    console.log("pre auth")

    return 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);
}
于 2020-10-02T22:37:20.193 回答