How to properly configure csurf with cookie-session in express?

337 views Asked by At

I'm trying to setup csrf protection using cookie-session as the csurf docs mention it explicitly, but loading my /form page returns a 500 and 'misconfigured csrf' is logged to the console.

import csrf from 'csurf'
import express from 'express'
import cookieSession from 'cookie-session'

const app = express()
const CookieSettings = {
  name: 'session',
  keys: ['keyone', 'keytwo'],
  httpOnly: true
}
//template engine stuff
app.use(cookieSession(CookieSettings))
app.use(csrf({ cookie: true }))
app.use(express.urlencoded({ extended: true }))

app.get('/form', (req, res) => {
  res.render('form.html', { csrf: req.csrfToken() })
}
app.post('/form', (req, res) => {
  console.log('CSRF: ', req.body._csrf)
  res.redirect(303, '/form')
}

app.listen(3000)
1

There are 1 answers

0
FumbDucker On

If you want to use cookies ["csrf({ cookie: true })"], you should use the library cookie-parser csurf_github otherwise, you should use session