我正在使用带有Google策略的护照进行身份验证
我的文件夹结构:
如果未设置req.user(我在使用google验证用户身份时设置了 req.user ),则我希望客户端被定向到enter.html而不能使用home.html。
完成身份验证后,用户应重定向到home.html
app.use(express.static())使两者都可用,这不是我想要的
google登录页面由auth / google提供
我还需要知道作为回调uri应该保留什么
在app.js中
我已经完成了mongodb配置
我已经完成了护照配置
下一步做什么?
在auth.js中
const router = require('express').Router();
const passport = require('passport');
router.route('/google')
.get(passport.authenticate('google', { scope: ["profile"] }));
router.route('/google/redirect')
.get(passport.authenticate('google'), (req, res, next) => {
// res.redirect what
});
module.exports = router;
要投放home.html
页,您可以重定向到受保护的本地路由。这是我将如何实施此示例。
auth.js
router.route('/google/redirect')
.get(passport.authenticate('google', { failureRedirect: '/' }), (req, res, next) => {
// Set to redirect to your home route / html page
res.redirect('/home')
});
为防止用户未经授权回家,您还应该在/home
路由中添加一个路由防护。
routes.js
const { checkAuth } = require('./guards'); // Protected routes
router.get('/home', checkAuth, async (req, res) => {
res.render('home')
});
guards.js
module.exports = {
checkAuth(req, res, next) {
if (req.isAuthenticated()) {
return next()
} else {
res.redirect('/')
}
},
}