8

我正在使用 express-jwt 来保护我的 API 端点,以便只有经过身份验证的用户才能访问我的 API。现在我还想根据用户的角色保护我的 API。例如,如果用户是管理员,则只能访问某些 API,如果他们是超级管理员,则只能访问其他一些 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 控制器功能中进行授权。这是唯一且推荐的方法吗?有没有更好的方法来做到这一点?关于最佳实践的任何建议?

4

1 回答 1

9

这是唯一且推荐的方法吗?

差不多,是的。

不过,这不是“控制器功能”。这是一个中间件示例,在这种情况下您要使用它。

一个更完整的例子是:


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

可以使用此设置的数十种变体,但这可以理解。

于 2016-03-31T18:12:37.417 回答