【问题标题】:Wrapping passport.authenticate inside a function doesn't work在函数内包装 passport.authenticate 不起作用
【发布时间】:2023-03-19 13:31:02
【问题描述】:

我正在尝试使用 Google OAuth2Strategy 对用户进行身份验证。我有以下路线

**server.get('/user/google', passport.authenticate('google', {scope: ['openid email profile']});
server.get('/user/google/callback', authenticate.authenticateGoogleCallback);** 

这完全正常。但是当我像我为回调所做的那样包装第一个身份验证时,它只是挂起。它是一个错误还是我做错了什么?

这就是我正在尝试的。

**server.get('/user/google', authenticate.authenticateGoogle); // NOT WORKING
server.get('/user/google', function(req,res,next){ // NOT WORKING
     passport.authenticate('google', {scope: ['openid email profile']});
});**

【问题讨论】:

    标签: node.js passport.js


    【解决方案1】:

    这就是我将 passport.authenticate 包装到我的一个项目中的方式:

    server.get('/user/google', (req, res, next) => {
      // making additional checks [you can skip this]
      const auth = req.header('Authorization')
    
      if (auth) {
        // this is what you are looking for
        passport.authenticate('jwt', { session: false })(req, res, next)
      } else {
        next()
      }
    })
    

    【讨论】:

      【解决方案2】:

      试试这个,让我们知道它是否有效。 (您必须在此链接http://passportjs.org/docs 中描述的函数末尾提供 (res,req,next))

      server.get('/user/google', function(req, res, next) {
        passport.authenticate('google', {
           scope: ['openid email profile']
        } ,function(err, user, info){
          res.send(user);
        })(req,res,next);
      })

      【讨论】:

      • 对于 Koa (koajs.com) 将 (req, res, next) 替换为 (ctx, next)
      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2020-11-14
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      相关资源
      最近更新 更多