Closed justkost closed 6 years ago
How do you conditionally mount or not mount the middleware?
You can do something like:
var app = new Koa()
var middleware = new CSRF({ ... })
app.post('/with-csrf', middleware, (ctx, next) => { ... })
app.post('/without-csrf', (ctx, next) => { ... })
app.post('/another/with-csrf', middleware, (ctx, next) => { ... })
async function conditionalCsrf(ctx, next) { debug('Entered conditional csrf middleware'); const request = ctx.request; debug(request.path, !.includes(request.path, '/webhook/')); if(!.includes(request.path, '/webhook/')) { return new CSRF(); // eslint-disable-line } await next(); // eslint-disable-line };
This is present between a bunch of middlewares. app.use(conditionalCsrf); I am trying to use it like this since I have a number of middlewares to be executed. I am unable to get it to work this way.
There's a similar example in the README:
app.use((ctx, next) => {
if (![ 'GET', 'POST' ].includes(ctx.method))
return next();
if (ctx.method === 'GET') {
ctx.body = ctx.csrf;
return;
}
ctx.body = 'OK';
});
So rather than checking the request method, you could check the request path.
The above example is just setting the generated csrf in the koa context. In the docs, above your written middleware there is app.use(new CSRF()) defined. I trying to conditionally mount that middleware.
Yes. You can avoid CSRF checks by not mounting the middleware.