我遇到了Passport.js模块和Express.js的问题。这是我的代码,我想使用谷歌提供商登录尝试。我总是得到这样的信息:错误:无法将用户序列化到会话中。当我试图查看序列化器中的内容时,我得到的消息“User object received by serializer”表明传递给序列化器的对象(passport.serializeUser)是Mongoose的Query的示例,而不是完整的用户对象。
Error: Failed to serialize user into session
at pass (C:\Users\vueForm\node_modules\passport\lib\authenticator.js:278:19)
at serialized (C:\Users\vueForm\node_modules\passport\lib\authenticator.js:283:7)
at C:\Users\vueForm\app.js:42:5
at pass (C:\Users\vueForm\node_modules\passport\lib\authenticator.js:291:9)
at Authenticator.serializeUser (C:\Users\vueForm\node_modules\passport\lib\authenticator.js:296:5)
at C:\Users\vueForm\node_modules\passport\lib\sessionmanager.js:33:10
at C:\Users\vueForm\node_modules\express-session\session\store.js:54:5
at C:\Users\vueForm\node_modules\connect-mongo\build\main\lib\MongoStore.js:377:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
字符串
的数据
app.use(
session({
secret: 'secret',
resave: false,
cookie: { httpOnly: false, secure: true, maxAge: 60 * 60 * 1000},
saveUninitialized: false,
store: MongoStore.create({mongoUrl: process.env.DB_URI}),
}))
app.use(passport.initialize());
app.use(passport.session());
connectToDatabase()
passport.serializeUser((user, done) => {
console.log("User objet get by serializer :", user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findOne(id, function (err, user) {
done(err, user);
});
});
passport.use(
new GoogleStrategy({
clientID: process.env.Google_clientID,
clientSecret: process.env.Google_clientSecret,
callbackURL: '/auth/google/callback',
},
async (accessToken, refreshToken, profile, done) => {
console.log("Info send to Google :", profile);
const existingUser = User.findOne({
providerId: profile.id,
})
if (existingUser) {
return done(null, existingUser);
} else {
const user = await new User({
googleId: profile.id,
displayName: profile.displayName,
email: profile.email,
photo: profile.photos[0].value,
}).save();
return done(null, user);
}
})
)
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback', (req,res,next)=>{
passport.authenticate('google', { failureRedirect: '/auth/google/error' }, async (error, user , info) => {
if (error){
return res.send({ message:error.message });
}
if (user){
try {
return res.send({
data: result.data,
message:'Login Successful'
});
} catch (error) {
return res.send({ message: error.message });
}
}
})(req,res,next);
res.redirect(`http://localhost:8080/home}`);
});
型
1条答案
按热度按时间fgw7neuy1#
问题出在反序列化用户函数中。User.findOne函数需要一个查询对象,但您直接将_id作为参数传递。另外,我认为明确地处理错误可能对可读性有好处。
字符串
出于好奇,你真的需要整个用户对象在每个API端点中都可用吗?你不能避免在每个请求期间查询数据库的需要吗?我是说你能不能别这么做,
型