我正在使用 express-jwt 来保护我的 API 端点,以便只有经过身份验证的用户才能访问我的 API。现在我也想根据用户的角色保护我的 API。例如,如果用户是管理员,则只能访问某些 API,如果他们是 super 管理员,则只能访问其他一些 API,等等。我该如何实现?我在 express-jwt github doc 中找到了这段代码片段:
app.get('/protected',
jwt({secret: 'shhhhhhared-secret'}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
看起来这段代码是在 API Controller 函数中进行授权。这是唯一和推荐的方式吗?有没有更好的方法来做到这一点?关于最佳实践的任何建议?
最佳答案
Is it the only and recommended way?
差不多,是的。
不过,这不是“ Controller 功能”。这是中间件的一个示例,这就是您在本例中要使用的。
一个更完整的例子是:
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);
可以使用此设置的许多变体,但这使想法得到了理解。
关于node.js - 使用 express-jwt 基于角色的授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340473/