使用CSRF的超级测试请求失败 [英] Supertest request with CSRF fails
问题描述
我有一个 Express 4应用程序,该应用程序使 csurf 的用户可以对API路由进行CSRF保护.该应用程序运行正常,并且CSRF保护确实在没有csrf-token
标头的请求会给出相应错误的情况下正常工作.
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.
我使用 Ava 进行测试,并使用 supertest 进行测试路线.启用CSRF检查后,以下测试失败,但是如果我删除中间件,则通过以下测试:
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.
推荐答案
我以前也遇到过supertest
和登录错误,但仍未解决,但使用supertest-session
似乎已为我解决了此问题.解决方法是替换:
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'
使用
import request from 'supertest-session'
一切都神奇地起作用.
这篇关于使用CSRF的超级测试请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!