Sergaros
Sergaros

Reputation: 831

How to set XSRF-TOKEN cookie in koa2 app?

I'm write node-koa2-angular app. And I need set XSRF-TOKEN cookie like in express app:

var csrfProtection = csrf({ cookie: true })

But in koa-csrf I cannot find this option and by default it's don't create cookie. Thanks for your help.

Upvotes: 0

Views: 554

Answers (1)

internetross
internetross

Reputation: 144

You're correct that koa-csrf does not create the cookie. Instead it introspects the cookie on the koa context at ctx.session. Check out where this happens in the code.

You'll need to add an additional middleware like koa-session to create the cookie. Your implementation should look something like:

const session = require('koa-session');
const CSRF = require('koa-csrf');

// set the session keys and add session support    
app.keys = ['secret']
app.use(session({}, app))

// add the CSRF middleware
app.use(new CSRF());

// your middleware here (e.g. parse a form submit)
app.use((ctx, next) => {
  if (ctx.method === 'GET') {
    ctx.state.csrf = ctx.csrf;
  }
  return next();
});

Upvotes: 1

Related Questions