护照和服务文件nodejs

发布时间:2020-07-07 17:03

我正在使用带有Google策略的护照进行身份验证

我的文件夹结构:

  • 意见
    • home.html
    • enter.html(这只有一个google +按钮
  • app.js
  • 路线
    • auth.js(用于Google登录的

如果未设置req.user(我在使用google验证用户身份时设置了 req.user ),则我希望客户端被定向到enter.html而不能使用home.html。

完成身份验证后,用户应重定向到home.html

app.use(express.static())使两者都可用,这不是我想要的

google登录页面由auth / google提供

我还需要知道作为回调uri应该保留什么

在app.js中

  1. 我已经完成了mongodb配置

  2. 我已经完成了护照配置

下一步做什么?

在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;
回答1

要投放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('/')
    }
  },
}
passport-google-oauth 相关推荐