我正在尝试弄清楚如何将 Oauth 策略(github)集成到我使用 Express 和 Websockets 的应用程序中。
我正在遵循本指南,该指南解释了如何使用 JWT token 而不是使用默认的通行证 session
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();
});
}
最佳答案
根据我的经验,passportjs 与 oauth 总是需要 session 才能运行,尽管有 session: false 选项。
我相信底层的 oauth 库依赖项无论如何都会寻找 session 。这很令人沮丧。
编辑:要添加更多详细信息,您链接到的示例使用默认策略,该策略不是基于 oauth 的。在这种情况下,您可以选择不使用 session 。您正在使用 github 策略,该策略使用 oauth 因此需要 session
关于node.js - 不使用 session 时 Passport.js 策略失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37923212/