【问题标题】:passport and serving files nodejs护照和服务文件nodejs
【发布时间】:2020-10-28 00:18:00
【问题描述】:

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

我的文件夹结构:

  • 查看次数
    • home.html
    • enter.html(这只有一个 google+ 按钮
  • app.js
  • 路线
    • auth.js(用于谷歌登录

如果 req.user 未设置,我希望客户端被定向到 enter.html 并且不能使用 home.html(req.user 在用户使用 google 进行身份验证时设置

一旦认证完成,用户应该被重定向到 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;

【问题讨论】:

    标签: javascript node.js express passport.js passport-google-oauth


    【解决方案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('/')
        }
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 2017-02-20
      • 2023-04-06
      • 1970-01-01
      • 2016-03-18
      • 2018-10-14
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多