1

我为 Express 路由器制作了一个自定义中间件,它允许我将我的 API 的某些端点列入白名单,以从身份验证中排除。但是,我有一条依赖于 URL 参数的路由,但我无法让我的中间件按预期工作。显然:profileId什么都不做,我的 API 端点仍然需要身份验证。

我需要将该路径排除在身份验证之外的原因是因为我的 React 前端应该向公众显示该数据(无需人们注册和登录)。任何提示如何解决这个问题?

const apiAuth = (req, res, next) => {
  let authRequired = true;

  if (
    req.path == "/api/users/register" ||
    req.path == "/api/users/login" ||
    req.path == "/api/profiles/:profileId"
  ) {
    authRequired = false;
  }

  if (authRequired == true) {
    // Auth check logic
  }
}
4

1 回答 1

2

有一些更好的方法可以处理中间件的要求,通常用于您建议的方法:

仅在您需要的路由上包含您的身份验证中间件:

const authenticationMiddleware = (req, res, next) => {
    // your login check logic
}

router.get('/api/users/me', authenticationMiddleware, (req, res, next) => {
    // your route logic, this endpoint now requires you to be logged in, as you have specified your authentication middleware in the declaration,
})

router.get('/api/profiles/:profileId', (req, res, next) => {
     // your route logic, this endpoint does not require you to be logged in as you have not put the middleware in the route delcaration
})

或者,根据调用路由的位置添加身份验证中间件:

router.get('/api/profiles/:profileId', (req, res, next) => {
    // your route logic, this endpoint does not require you to be logged as we have not told our router to use the middleware yet
})

router.use(authenticationMiddleware)

router.get('/api/users/me', (req, res, next) => {
    // your route logic, this endpoint now requires you to be logged in, as the router has been told to use the middleware at this point.
})

为什么要使用这些方法?尝试将您所做的所有router或调用视为添加到堆栈中,该堆栈用于处理对您的站点或 API 的调用。app当它通过查找路线工作时,它将调用它在途中找到的任何中间件。

这解决了必须声明需要或不需要特定身份验证的路由列表或数组等问题。

如果你想让它工作,你还需要确保调用next()你的中间件,因为这告诉 express 继续遍历它拥有的所有路由/中间件。

于 2019-03-05T11:23:28.550 回答