成功使用Google账户登录后,在回调请求中,req.user
被设置为正确的用户,req.isAuthenticated()
为true。太好了!
然而,任何后续请求都会将req.user
设置为未定义。无论我做什么。
这个问题在passport-google-auth2和passport-google-auth中都存在。
以下是我的index.js
的样式:
app.set('views', './src/express/views');
app.set('view engine', 'jsx');
app.engine('jsx', expressReactViews.createEngine({ beautify: true }));
app.use(express.static('./dist'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use( bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'keyboard cat',
proxy: true,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
// user is passed here correctly
done(null, user.id);
});
passport.deserializeUser(function(userId, done) {
db.connect(function(error, connection) {
if(error) {
done(error);
}
else {
users.find(connection, userId, function (user) {
connection.close();
// user is populated here, don't worry :)
done(null, user);
});
}
});
});
passport.use(googleStrategy);
这就是 googleStrategy
的样子:
module.exports = new GoogleStrategy(
{
clientID: '[FAKE]',
clientSecret: '[FAKE]',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
function(accessToken, refreshToken, profile, done) {
db.connect((error, connection) => {
if(error) {
done(error);
}
else {
users.findOrCreateFromGoogleProfile(connection, profile, (error, user) => {
connection.close();
done(error, user);
});
}
});
}
);
这是我的
auth
路由器的样子:router.route('/google/callback').get(passport.authenticate('google', {
failureRedirect: '/error'
}), function(req, res) {
// here everything works. req.user is correctly set and req.isAuthenticated() is true
res.redirect('/index');
});
router.route('/google').get(passport.authenticate('google', {
scope: ['https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email']
}));
module.exports = router;
我的操作有误吗?
req.user
是存在的,但在未来的请求中却不存在。我相信这与我的应用程序无法持久化会话或 cookie 有关。如果您知道如何检查它,我将不胜感激。 - Andre Pena