PassportSocketIo.authorize不会调用成功或失败回调

时间:2020-10-02 22:17:24

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

我最近实现了用于对我的Express服务器进行身份验证的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”,但没有来自授权功能的消息,也没有任何错误消息。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

namespace.use方法是一种将中间件(函数)添加到套接字的方法。因此,它期待一个功能。另一方面,passportSocketIo.authorize返回的是中间件功能,您可以检查代码here。 因此,您有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);
}