koajs / csrf

CSRF tokens for koa
MIT License
264 stars 32 forks source link

Can i disable CSRF check for some routes? #46

Closed justkost closed 6 years ago

stephenmathieson commented 6 years ago

Yes. You can avoid CSRF checks by not mounting the middleware.

arunrreddy commented 5 years ago

How do you conditionally mount or not mount the middleware?

stephenmathieson commented 5 years ago

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) => { ... })
arunrreddy commented 5 years ago

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.

stephenmathieson commented 5 years ago

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.

arunrreddy commented 5 years ago

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.