基于angular色的授权与exress-jwt?

我正在使用express-jwt来保护我的API端点,以便只有经过身份validation的用户才能访问我的API。 现在我也想根据用户angular色来保护我的API。 例如,用户只能访问一些API,如果他们是pipe理员,其他一些如果他们是超级pipe理员等。我怎么能实现这一点? 我在express-jwt github doc中find了这段代码片段:

app.get('/protected', jwt({secret: 'shhhhhhared-secret'}), function(req, res) { if (!req.user.admin) return res.sendStatus(401); res.sendStatus(200); }); 

它看起来像这个代码是在API控制器function授权。 这是唯一和推荐的方式吗? 有没有更好的方法来做到这一点? 任何有关这方面的最佳做法的build议?

这是唯一和推荐的方式吗?

很多,是的。

虽然这不是“控制器function”。 这是中间件的一个例子,在这种情况下就是你想要使用的。

一个更完整的例子是:

 var router = new express.Router(); // process jwt stuff var processjwt = jwt({secret: 'shhhhhhared-secret'}); // authorization check function authorizationCheck(req, res, next) { if (!req.user.admin) { return res.sendStatus(401); } else { // move to the next middleware, cause it's ok next(); } } // the real route handler function myRouteHandler(req, res){ doSomeWork(function(err, data){ if (err) { return next(err); } res.json(data); }); } // put it all together router.use("/protected", processjwt, authorizationCheck); router.get("/protected", myRouteHandler); 

在这个设置上有几十个可以使用的变体,但是这个想法得到了解决。