不使用会话时,Passport.js策略失败

时间:2016-06-20 12:57:24

标签: node.js oauth-2.0 passport.js jwt

我正在试图弄清楚如何将Oauth策略(github)集成到使用express和websockets的应用程序中。

我正在按照本指南解释如何使用JWT令牌而不是使用默认的护照会话

https://blog.hyphe.me/token-based-authentication-with-node/

这是我到目前为止的代码

  app.use(passport.initialize())
  app.get('/auth/github',passport.authenticate('github',{session:false}),serialize, generateToken, respond)

  app.get('/auth/github/callback',passport.authenticate('github',{failureRedirect:'/'}),
    function(req,res){
      res.redirect('/')
    }
  )

当我尝试通过github登录时 - 我收到以下错误

Error: Failed to serialize user into session
    at pass (/home/avernus/Desktop/experiments/oauth/node_modules/passport/lib/authenticator.js:271:19)
    at Authenticator.serializeUser (/home/avernus/Desktop/experiments/oauth/node_modules/passport/lib/authenticator.js:289:5)
    at IncomingMessage.req.login.req.logIn (/home/avernus/Desktop/experiments/oauth/node_modules/passport/lib/http/request.js:50:29)
    at Strategy.strategy.success (/home/avernus/Desktop/experiments/oauth/node_modules/passport/lib/middleware/authenticate.js:235:13)
    at verified (/home/avernus/Desktop/experiments/oauth/node_modules/passport-oauth2/lib/strategy.js:177:20)
    at Strategy._verify (/home/avernus/Desktop/experiments/oauth/passport.js:13:12)
    at /home/avernus/Desktop/experiments/oauth/node_modules/passport-oauth2/lib/strategy.js:193:24
    at /home/avernus/Desktop/experiments/oauth/node_modules/passport-github/lib/strategy.js:174:7
    at passBackControl (/home/avernus/Desktop/experiments/oauth/node_modules/oauth/lib/oauth2.js:125:9)
    at IncomingMessage.<anonymous> (/home/avernus/Desktop/experiments/oauth/node_modules/oauth/lib/oauth2.js:143:7)

我不确定问题究竟在哪里

这是我的github策略

passport.use(new githubStrategy({
  clientID:'********',
  clientSecret:'*******',
  callbackURL:'http://localhost:3000/auth/github/callback'
  },
  function(accessToken,refreshToken,profile,done){
    console.log('accessToken: ',accessToken,' refreshToken: ',refreshToken,' profile: ',profile)
    return done(null,profile)
  }
))

我能够从github

成功获取个人资料

序列化功能

function serialize(req, res, next) {  
  db.updateOrCreate(req.user, function(err, user){
    if(err) {return next(err);}
    // we store the updated information in req.user again
    req.user = {
      id: user.id
    };
    next();
  });
}

2 个答案:

答案 0 :(得分:2)

根据我的经验,带有oauth的passportjs总是需要会话来操作,尽管会话:false选项。

我相信潜在的oauth库依赖关系会查找会话,无论如何。它非常令人沮丧。

编辑:要为此添加更多详细信息,您要链接的示例使用默认策略,该策略不是基于oauth的。在这种情况下,您可以选择不使用会话。你正在使用使用oauth的github策略,因此需要会话

答案 1 :(得分:1)

您是否错过了回调中的{session:false}选项?

app.get('/auth/github/callback',passport.authenticate('github',{failureRedirect:'/', session: false}),
function(req,res){
  res.redirect('/')
})

我猜对了,因为我从未使用需要回调的策略。但我想,护照会尝试在回调中序列化用户,因为这是您从Github收到个人资料的地方。