我正在使用Google验证用户身份,并将会话存储在Redis服务器上:
web / auth-routes / index.js
import express from 'express';
import session from 'express-session';
import connectRedis from 'connect-redis';
import google from './providers/google';
const RedisStore = connectRedis(session);
const router = express.Router();
router.use(session({
key: 'user_sid',
cookie: { httpOnly: true },
secret: process.env.SESSION_SECRET,
store: new RedisStore({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
ttl: 172800,
}),
saveUninitialized: false,
resave: false,
}));
router.use('/google', google);
module.exports = router;
网络/身份验证路由/提供商/谷歌
import express from 'express';
import passport from 'passport';
import jwt from 'jsonwebtoken';
import passportSetup from '../../passport-setup';
const router = express.Router();
router.get('/', (req, res, next) => {
req.session.callback = req.query.callback;
next();
}, passport.authenticate('google', { scope: ['profile'] }));
router.get(
'/redirect',
passport.authenticate('google'),
(req, res) => {
const token = jwt.sign({
username: req.user.username,
googleID: req.user.googleID,
}, process.env.JWT_SECRET);
res.cookie('token', token, {
httpOnly: true,
secure: true,
});
res.redirect(req.session.callback);
},
);
module.exports = router;
我了解到该会话已存储在Redis上,并且已参考该会话在浏览器中设置了cookie。现在,此cookie和所有cookie一样,以每个请求req.cookies.user_id
的形式从浏览器发送到服务器。
我的问题是,如何验证此cookie(req.cookies.usrr_id
)是否在服务器上收到Redis时(即在每次加载/刷新页面之后)仍引用Redis上的有效条目?而且,我应该吗?还是在其他地方遵循了更好的标准?回购位于https://github.com/amitschandillia/proost/tree/master/web。
此外,到目前为止,我阅读的有关该主题的每篇文章都说,会话ID可从req.sessionID
获得。但是,我的服务器代码段中包含以下代码:
server.get('*', (req, res) => {
console.log(req.session);
console.log(req.sessionID);
handle(req, res);
});
在两个日志上都保留未定义的返回值。难道我做错了什么?我一定是!