Super test, secure REST API

I am writing an integration test for the REST API protected by jwt . One API POST /user/token jwt returns jwt with username and password in mind, and this token is then used for a list of operations, such as:

 GET /user/:id 

If the route uses jwt({secret: secret.secretToken}) , then the token is included in the http Authorization header.

When testing with a supertest, I can have nested testing, but first I want to get a token, and then use this token for another work test.

 POST /user/token => 12345 GET /user/:id, `Authorization Bearer 12345` GET /user/:foo, `Authorization Bearer 12345` 

To avoid generating a new token for each operation test (see below), but use only one generated 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 
+5
source share
2 answers

Do you want to do a single POST on /user/token and then use the token obtained in each test case? If so, then use the hook before used test environment (Mocha?) And save the token in a variable, for example.

 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); }); }); 
+16
source

You need to set Authorization as a โ€œDenominatorโ€ + token

  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); }); 
0
source

Source: https://habr.com/ru/post/1205040/


All Articles