【问题标题】:Passport.js: how to protect ALL routes?Passport.js:如何保护所有路线?
【发布时间】:2019-07-03 22:59:12
【问题描述】:

我按照本地护照的 passport.js 文档:http://www.passportjs.org/docs/authorize/

当我将我的用户发送到 /login 时,他们已通过身份验证,但在该文档中我找不到如何授权我的用户。

我试过这个,但它给了我一个bad request

router.get('/somepage', passport.authenticate('local'), function(req, res, next) {

});

我正在寻找同时保护我所有页面的方法。我正在使用 Express 4.16 并使用不同的路由文件来拆分我的路由。

山姆

【问题讨论】:

    标签: node.js passport.js passport-local


    【解决方案1】:

    您可以使用middleware 和一个小技巧在策略之间进行切换

    示例:

    const allowUrl = ['public', 'nonprivate','home'];
    
    
    const authenticationMiddleware = (whiteList =[]) => (req, res, next) => {
        if(whiteList.find(req.baseUrl)) {
          next();
        }
    
        if (req.isAuthenticated()) {
          return next()
        }
        res.redirect('/');
    }
    
    
    app = express();
    app.use(passort.initialize());
    app.use(authenticationMiddleware(allowUrl));
    app.use(apiRouter);
    
    
    app.listen(3000, ()=> console.log('hello internet');
    

    【讨论】:

    • 为什么要创建一个返回函数的函数?
    • 哦,老实说,我只是从护照文件中复制和粘贴哈哈 xD!有时我相信人们认为它比 es6 语法更常见。更新
    【解决方案2】:

    您可以像下面这样添加中间件代码

    router.get('/', isAuthenticated, function(req, res) {
       //your next function 
    });
    function isAuthenticated(req, res, next) {
      // do any checks you want to in here
    
      // CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
      // you can do this however you want with whatever variables you set up
      if (req.user.authenticated)
          return next();
    
      // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
      res.redirect('/');
    }
    

    【讨论】:

    • 在这种情况下,'/'(root iirc)路由会是包含登录页面的路由吗?
    【解决方案3】:

    由于我希望所有路由(除了登录路由之外)都通过授权,因此我解决了如下问题:

    var ensureAuthenticated = function(req, res, next) {
        if (req.isAuthenticated()) return next();
        else res.redirect('/login')
    }
    
    // usersRouter contains all open routes like '/login':
    app.use('/', usersRouter);
    
    // From here on, all routes need authorization:
    app.use(ensureAuthenticated);
    
    app.use('/', indexRouter);
    app.use('/api/foo', fooRouter);
    app.use('/api/bar', barRouter);
    

    【讨论】:

    • 恕我直言,我的解决方案更好,因为您可以在任何地方添加 ensureAuthenticated 函数,不要关心受保护/不受保护的 api 的位置(在中间件之前或之后)。它由allowUrl 数组控制,作为我上面的解决方案。
    【解决方案4】:

    我不确定“但在该文档中我找不到如何授权我的用户”是什么意思。 Passportjs 不会授权任何用户。它是一个身份验证中间件。授权不同于身份验证。

    我认为您正在寻找应用程序级中间件。您必须使用 app.use 对服务器的每个请求进行身份验证。 你可以在这里读更多关于它的内容。 https://expressjs.com/en/guide/using-middleware.html#middleware.application

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      相关资源
      最近更新 更多