Passport.js: 如何保护所有路由?

Passport.js: how to protect ALL routes?

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

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

我已经试过了,但这给了我 bad request:

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

});

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

山姆

我不确定你所说的 "but nowhere in that document can I find how to authorise my users" 是什么意思。 Passportjs 不会授权任何用户。它是一个身份验证中间件。授权不同于认证。

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

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

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

您可以使用 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');

因为我想让所有的路由(当然除了登录路由)都通过授权,所以我解决了:

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);