node.js - 使用 express-jwt 基于角色的授权?

标签 node.js express express-jwt

我正在使用 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/

相关文章:

sql - Sequelize 查询 关联的性能问题

javascript - 在没有 POST 的情况下处理 Remix.run 中的操作

Node.js Express - 在完成处理整个请求之前提供 HTTP 响应

node.js - 路由上记录请求方法

node.js - Express-jwt - isRevoked : done is not a function

node.js - 本示例中 JWT token 存储在哪里?

node.js - 如何使用 NodeJs 缩小 Docker 镜像的大小

javascript - 如何在 Node.js 中使用 getstream.io 构建新闻提要?

javascript - server.js 文件外部的快速路由

express - 使用 except 处理 express-jwt 中的参数化路由