简体   繁体   中英

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

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)

if you want to use cookies ["csrf({ cookie: true })"], you should use the lib 'cookie-parser' csurf_github otherwhise, you should use session

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM