egg icon indicating copy to clipboard operation
egg copied to clipboard

命名路由如何鉴权

Open qzcsgs opened this issue 4 years ago • 3 comments

访问 GET: /api/goods/1234456 时我该如何鉴权?

// router.js
router.resources('goods', '/api/goods', controller.goods);

// 鉴权中间件
async function(ctx, next) {
    const routerWhiteList = [
      'post:/api/goods',
      'get:/api/goods/:id',
    ];
    const url = ctx.url;
    const params = ctx.params; // undefined
    
    const flag = routerWhiteList.includes(`${ctx.method.toLocaleLowerCase()}:${url}`);
    if (flag) {
      await next();
    } else {
      // ...
    }
  };

qzcsgs avatar Feb 24 '22 06:02 qzcsgs

我也遇到了这个问题,想着给路由设置了别名,但又没找到在中间件中获取别名的方法

ZHAOzn avatar Jun 27 '22 08:06 ZHAOzn

console.log(ctx.routerName); console.log(ctx.routerPath); console.log(ctx._matchedRouteName);] 试试这三个参数,第一个是获取路由别名,第二个是获取路由path“user/:id”。

ZHAOzn avatar Jun 27 '22 09:06 ZHAOzn

router 是洋葱模型最里面的那个 Middleware,所以你加全局 Middleware 是检测不到的,只能用 Router Middleware

  const authFn = async (ctx, next) => {
    console.log(ctx.routerName);
    await next();
  }
  router.get('home', '/', authFn, controller.home.index);

或者自行封装一个函数,示例如下:

module.exports = app => {
  const { router, controller } = app;
  
  const authFn = async (ctx, next) => {
    console.log(ctx.routerName);
    await next();
  }

  function registryRouter(name, path, action) {
    router.get(name, path, authFn, action);
  }

  registryRouter('home', '/', controller.home.index);
};

atian25 avatar Jun 27 '22 09:06 atian25