Supertest,测试安全的 REST API [英] Supertest, test secure REST API
问题描述
我正在为受 jwt
保护的 REST API 编写集成测试.一个 API 操作 POST /user/token
返回一个 jwt
给定一个 username
和一个 password
并且这个令牌是然后用于操作列表,例如:
I am writing an integration test for a REST API protected by a jwt
.
One API operation POST /user/token
is returning a jwt
given a username
and a password
and this token is then used for a list of operations such as:
GET /user/:id
路由在哪里使用jwt({secret:secret.secretToken})
,所以token包含在HTTP头Authorization
中.
Where the route is using jwt({secret: secret.secretToken})
, so the token is included into the HTTP header Authorization
.
在使用supertest进行测试时,我可以进行嵌套测试,但我想先获取token,然后使用此token测试其他操作.
When testing with supertest, I can have nested testing but I want to first get the token, then use this token for testing other operations.
POST /user/token => 12345
GET /user/:id, `Authorization Bearer 12345`
GET /user/:foo, `Authorization Bearer 12345`
如何避免为每个操作测试生成一个新令牌(见下文),但只使用一个由 POST/user/token 生成的令牌.
How to avoid generating a new token for every operation testing (see below) but use only a single one generate by POST /user/token.
it('should get a valid token for user: user1', function(done) {
request(url)
.post('/user/token')
.send({ _id: user1._id, password: user1.password })
.expect(200) // created
.end(function(err, res) {
// test operation GET /user/:id
推荐答案
您想对 /user/token
执行单个 POST,然后使用在每个测试用例中收到的令牌?如果是这样,则使用您正在使用的测试框架(Mocha?)的 before
钩子并将令牌存储到变量中,例如
You want to perform single POST to /user/token
and then use the token received in every test case? If so, then use the before
hook of the test framework you are using (Mocha?) and store the token to a variable, e.g.
describe('My API tests', function() {
var token = null;
before(function(done) {
request(url)
.post('/user/token')
.send({ _id: user1._id, password: user1.password })
.end(function(err, res) {
token = res.body.token; // Or something
done();
});
});
it('should get a valid token for user: user1', function(done) {
request('/get/user')
.set('Authorization', 'Bearer ' + token)
.expect(200, done);
});
});
这篇关于Supertest,测试安全的 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!