首页 > 解决方案 > 基于 Auth0 范围授权 FeathersJs 服务

问题描述

我的 feathers.js API 中有一个用户服务。我想让 find 方法仅适用于已阅读的经过身份验证的用户:用户范围集。

express-jwt用作身份验证的中间件。我尝试过使用express-jwt-authz授权,但我不能,因为req在钩子中不可用。express-jwt库在 req.user 中设置范围

用法 JWT 身份验证中间件使用 JWT 对调用者进行身份验证。如果令牌有效,则 req.user 将设置为解码的 JSON 对象,以供以后的中间件用于授权和访问控制。

有没有办法可以访问钩子内 access_token 中的范围?

我希望能够做这样的事情:

module.exports = {
  before: {
    all: [],
    find: [ authorize(['read:users']) ],
    get: [ authorize(['read:users'])],
    create: [ authorize(['write:users']) ],
    update: [ authorize(['write:users'])   ],
    patch: [ authorize(['write:users'])  ],
    remove: [ authorize(['write:users'])  ]
  }
};

标签: expressauth0feathersjs

解决方案


通过添加一个将 req.user 数据添加到 req.feathers.scope 的中间件来解决它。

我的src/middleware/index.js档案

const addUserToReq = function(req, res, next) {
  req.feathers.user = req.user; next();
};

module.exports = function (app) {
  app.use(checkJwt); // express-jwt logic
  app.use(addUserToReq);
};

然后在钩子里面我可以像这样访问这个信息

module.exports = function(expectedScopes) {
  return context => {
      let scopes = context.params.user.scope;
    }
  };
};

推荐阅读