I have an Express 4 application that makes user of csurf for CSRF protection on API routes. The application is working perfectly and CSRF protection is indeed working where requests without the csrf-token
header will give the appropriate error.
I make use of Ava for testing with supertest for testing routes. The following test fails when CSRF checking is enabled but passes if I remove the middleware:
test('booking api no auth', async t => {
t.plan(4)
const server = await request(makeServer(t.context.config, t.context.connection))
const csrf = await server
.get('/')
.then(res => new JSDOM(res.text))
.then(dom => dom.window.document.querySelector('meta[name="csrf_token"]'))
.then(csrfMeta => csrfMeta.getAttribute('content'))
const GET = await server
.get('/v2/Booking')
.set('csrf-token', csrf)
const POST = await server
.post('/v2/Booking')
.set('csrf-token', csrf)
.send({
name: 'Test',
description: 'Test',
category: 'diving',
minimumPax: 1,
maximumPax: 2,
priceAdult: 1,
priceChild: 1
})
const res = { GET, POST }
t.is(res.GET.status, 403)
t.deepEqual(res.GET.body, text['403'])
t.is(res.POST.status, 201)
t.truthy(res.POST.body._id)
})
I have verified that the header is indeed set in the request. Any ideas or suggestions for alternative libraries that works is appreciated.
I've previously also had errors with supertest
and logging in, still unresolved, but using supertest-session
seems to have fixed this for me. Fix was to replace:
import request from 'supertest'
with
import request from 'supertest-session'
and everything magically works.