我正在尝试对Express服务器进行身份验证。在正面,我正在使用React.js 为了验证用户身份,我将护照与oauth Google Flow配合使用。
这是我的路线处理程序:
const passport = require('passport');
const requireLogin = require('../middlewares/requireLogin');
module.exports = app => {
app.get('/admin', passport.authenticate('google', {
scope: ['profile', 'email'],
failureFlash: true,
}));
app.get(
'/auth/google/callback',
passport.authenticate('google'),
(req, res) => {
res.redirect('/panel');
}
);
app.get('/auth/logout', (req, res) => {
req.logout();
res.redirect('/login')
});
app.get('/current_user', (req, res) => {
res.send(req.user);
});
};
如您所见,当我从Google获得成功回调时(即用户已成功登录),我正在重定向到React Router关心的“ / panel”(面板是只有一些用户可以访问的页面进来吧)。我有注销按钮,它会触发“ / auth / logout”并再次重定向到登录页面。以上所有方法都可以正常工作,但是当我手动在地址栏http://localhost:3000/panel#中写入内容时,即使我已经成功注销,仍然可以登录。我可以访问用户模型(已登录),该模型通过req.user更改为false(注销)。
我试图自己弄清楚,但不能做到。我正在尝试使用中间件:
module.exports = (req, res, next) => {
if (!req.user) {
return res.status(401).send({ error: 'You must be logged in'})
}
next();
};
...但是无法在此逻辑中将其放在正确的位置。谢谢!