Node.js 如何在自定义中间件中使用csurf?
我已经设法让Node.js 如何在自定义中间件中使用csurf?,node.js,express,csrf,Node.js,Express,Csrf,我已经设法让csurf作为常规中间件在我的express应用程序中工作。但是,我想将它添加到我的自定义身份验证中间件中,以避免在每个路由中都包含csurf,也避免忘记使用它。如何在自定义中间件中调用csurf 例如,假设我使用此中间件使用express session来限制登录用户的访问: export const auth = async (req, res, next) => { const { uid } = req.session; try { const use
csurf
作为常规中间件在我的express
应用程序中工作。但是,我想将它添加到我的自定义身份验证中间件中,以避免在每个路由中都包含csurf
,也避免忘记使用它。如何在自定义中间件中调用csurf
例如,假设我使用此中间件使用express session
来限制登录用户的访问:
export const auth = async (req, res, next) => {
const { uid } = req.session;
try {
const user = await User.query().findById(uid);
req.session.role = user.role;
next();
} catch {
throw new PrivateRouteError();
}
};
我有办法做到这一点,但我无法实现它。以下是我尝试过的:
export const auth = async (req, res, next) => {
const csrf = csurf({ cookie: true, ignoreMethods: [] });
csrf(req, res, async () => {
const { uid } = req.session;
try {
const user = await User.query().findById(uid);
req.session.role = user.role;
next();
} catch {
throw new PrivateRouteError();
}
});
};
但是,结果是csurf
不会阻止对丢失的CSRF令牌的访问,并且privateroutererror
不会被捕获并使应用程序崩溃(如果用户未通过身份验证,如果他们通过身份验证,则可以正常工作)
是否有一种简洁的方法将
csurf
捆绑到我的中间件中,或者我应该手动将其添加到使用auth
中间件的所有路由中?好的,我昨晚显然想得太多了。去掉next()
调用并将csurf
内容放在catch块之后就足够了
export const auth = async (req, res, next) => {
const { uid } = req.session;
try {
const user = await User.query().findById(uid);
req.session.role = user.role;
} catch {
throw new PrivateRouteError();
}
const csrf = csurf({ cookie: true, ignoreMethods: [] });
csrf(req, res, next);
};