使用 PassportJS 阻止 API

Prevent APIs using PassportJS

我有如下终点:

app.post(api + '/channels/:channel_id/albums', user.ensureAuthenticated, album.create);
app.get(api + '/channels/:channel_id/albums/published', user.ensureAuthenticated,album.publishedAlbums);
app.get(api + '/channels/:channel_id/albums', user.ensureAuthenticated, album.findAll);

一切正常,但是我很烦在每个端点都放user.ensureAuthenticated,有什么方法可以一次放完user.ensureAuthentication吗?

例如:Laravel 有这样的选项,比如 beforeAuth 你做一个 if 并且在里面你把你想要保护的所有端点。

喜欢前任:

if(user.ensureAuthenticated){
  // endpoints declariations
}else{
  // redirect to login
}

谢谢

你会在这里找到答案: Only allow passportjs authenticated users to visit protected page

尤其是这种代码:

//checks to be sure users are authenticated
app.all("*", function(req, res, next){
if (!req.user) 
    res.send(403);
else
    next();
});

所有端点都将受到保护。