0

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

我的文件夹结构:

  • 意见
    • 主页.html
    • enter.html(这只有一个 google+ 按钮
  • 应用程序.js
  • 路线
    • auth.js(用于谷歌登录

我希望客户端被定向到 enter.html 并且如果未设置 req.user 则无法使用 home.html (当用户使用 google 进行身份验证时设置了 req.user )

完成身份验证后,应将用户重定向到 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;
4

1 回答 1

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

路由.js

const { checkAuth } = require('./guards'); // Protected routes 
router.get('/home', checkAuth, async (req, res) => {
  res.render('home')
});

守卫.js

module.exports = {
  checkAuth(req, res, next) {
    if (req.isAuthenticated()) {
      return next()
    } else {
      res.redirect('/')
    }
  },
}
于 2020-07-07T17:37:09.847 回答