passport and serving files nodejs
我正在使用带有谷歌策略的护照进行身份验证
我的文件夹结构:
-
意见
- 主页.html
- enter.html(这只有一个谷歌按钮)
- 应用程序.js
-
路线
- auth.js(用于谷歌登录)
我希望客户端被定向到 enter.html 并且如果没有设置 req.user 则不能使用 home.html (当用户使用 google 进行身份验证时设置了 req.user )
一旦身份验证完成,用户应该被重定向到 home.html
app.use(express.static()) 使它们都可用,这不是我想要的
google 登录页面来自 auth/google
而且我还需要知道我应该保留什么作为回调 uri
在 app.js
我已经完成了mongodb的配置
我已经完成了护照配置
接下来要做什么?
在 auth.js
1 2 3 4 5 6 7 8 9 | 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; |
要为
auth.js
1 2 3 4 5 | router.route('/google/redirect') .get(passport.authenticate('google', { failureRedirect: '/' }), (req, res, next) => { // Set to redirect to your home route / html page res.redirect('/home') }); |
为了防止用户在未经授权的情况下回家,你还应该在你的
routes.js
1 2 3 4 | const { checkAuth } = require('./guards'); // Protected routes router.get('/home', checkAuth, async (req, res) => { res.render('home') }); |
guards.js
1 2 3 4 5 6 7 8 9 | module.exports = { checkAuth(req, res, next) { if (req.isAuthenticated()) { return next() } else { res.redirect('/') } }, } |