Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript passport和服务文件节点_Javascript_Node.js_Express_Passport.js_Passport Google Oauth - Fatal编程技术网

Javascript passport和服务文件节点

Javascript passport和服务文件节点,javascript,node.js,express,passport.js,passport-google-oauth,Javascript,Node.js,Express,Passport.js,Passport Google Oauth,我正在使用passport和google策略进行身份验证 我的文件夹结构: 观点 home.html enter.html(只有一个google+按钮) app.js 路线 auth.js(用于谷歌登录) 如果没有设置req.user,我希望客户端被引导到enter.html,并且不能使用home.html(当用户使用google进行身份验证时设置req.user) 身份验证完成后,应将用户重定向到home.html app.use(express.static())使它们都可用

我正在使用passport和google策略进行身份验证

我的文件夹结构:

  • 观点
    • home.html
    • enter.html(只有一个google+按钮)
  • app.js
  • 路线
    • auth.js(用于谷歌登录)
如果没有设置req.user,我希望客户端被引导到enter.html,并且不能使用home.html(当用户使用google进行身份验证时设置req.user)

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

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

谷歌登录页面由auth/google提供

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

在app.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;
  • 我已经完成了mongodb配置

  • 我已经完成了passport配置

  • 下一步怎么办

    在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('/')
        }
      },
    }