我为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
}
}
答案 0 :(得分: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
或app
调用添加到堆栈中,该堆栈明确表示用于处理对您的网站或API的调用。在寻找路由的过程中,它将找到的方式调用任何中间件。
这解决了必须声明不需要或不需要特定身份验证等内容的路由列表或路由的问题。
如果您希望中间件工作,还需要确保在中间件中调用next()
,因为这表明快递将继续遍历它所拥有的所有路由/中间件。