Supertest request with CSRF fails

拟墨画扇 提交于 2019-12-11 15:23:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/44827846/supertest-request-with-csrf-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!