我已经在Google,Twitter和Facebook的API oauth2登录名上实现了
一切正常,直到我注意到1小时后护照不再能够识别存储的cookie(包含有关用户的所有信息的connect.sid)。 cookie仍然存在,但是当护照反序列化它时,req.user是不确定的,我绝对需要req.user.id。
这样的行为正常吗?即使Cookie的内容“过期”,我如何正确反序列化该Cookie?
我对护照使用以下策略:passport-google-oauth20,passport-twitter,passport-facebook
我也可以尝试将用户的ID存储在cookie中,但是由于序列化的cookie已经存储了有关该用户的所有信息,因此这似乎是一种黑客。
const express = require('express');
const app = express();
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const cookieSession = require('cookie-session');
// cookieSession config
app.use(cookieSession({
maxAge: 24 * 60 * 60 * 1000, // One day in milliseconds
keys: ['randomstringhere']
}));
app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions
// Strategy config
passport.use(new GoogleStrategy({
clientID: 'YOUR_CLIENTID_HERE',
clientSecret: 'YOUR_CLIENT_SECRET_HERE',
callbackURL: 'http://localhost:8000/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
done(null, profile); // passes the profile data to serializeUser
}
));
// Used to stuff a piece of information into a cookie
passport.serializeUser((user, done) => {
done(null, user);
});
// Used to decode the received cookie and persist session
passport.deserializeUser((user, done) => {
done(null, user);
});
// Middleware to check if the user is authenticated
function isUserAuthenticated(req, res, next) {
if (req.user) {
next();
} else {
res.send('You must login!');
}
}
// Routes
app.get('/', (req, res) => {
res.render('index.ejs');
});
// passport.authenticate middleware is used here to authenticate the request
app.get('/auth/google', passport.authenticate('google', {
scope: ['profile'] // Used to specify the required data
}));
// The middleware receives the data from Google and runs the function on Strategy config
app.get('/auth/google/callback', passport.authenticate('google'), (req, res) => {
res.redirect('/secret');
});
// Secret route
app.get('/secret', isUserAuthenticated, (req, res) => {
res.send('You have reached the secret route');
});
// Logout route
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.listen(8000, () => {
console.log('Server Started!');
});```