【问题标题】:Prevent APIs using PassportJS使用 PassportJS 阻止 API
【发布时间】:2015-03-30 12:16:28
【问题描述】:

我有如下端点:

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
}

感谢

【问题讨论】:

    标签: javascript node.js passport.js


    【解决方案1】:

    你会在这里找到答案: 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();
    });
    

    所有端点都将受到保护。

    【讨论】:

    • 这段代码之后没有user.ensureAuthenticated参数。
    • 如果我的路线不在一个文件中怎么办?
    • 没问题,只需将 app.all 路由放在所有代码之前即可。
    • 这实际上是问题所在 :),bc 我不希望那些其他路由受到保护,因为其中一些应该是公开的。
    • 您是否可以在路由子集上使用白名单系统,使用此示例中的函数:stackoverflow.com/questions/11650489/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2013-11-28
    • 2021-05-14
    相关资源
    最近更新 更多