Passport JWT auth in unit test - connector opens

I have an emotional time trying to check secure routes that use the JWT passport strategy with an authorization header.

I tried the axioms, supertest, superagent, and I get the same error - "socket hang up":

Error: socket hang up
at createHangUpError (_http_client.js:253:15)
at Socket.socketOnEnd (_http_client.js:345:23)
at emitNone (events.js:91:20)
at Socket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9) code: 'ECONNRESET', response: undefined }

This works fine in the dev environment, it only happens in the test environment - unit tests or dev env pointing to test DB / users.

I know that this error means that the connection was closed by a server failure or a syntax error, however there are no syntax errors. The endpoint does not pass by the passport certificate:

passport.authenticate('jwt'...

Why? How can this be solved?

End point:

router.route('/private')
  .get(
    passport.authenticate('jwt', { session: false }), (req, res, next) => {
      res.json({ allTheThings: true });
  })

Test:

describe('GET /api/private', () => {
  it('should work', () => {
    const USER_JWT_VALID = 'JWT asdf.....';

    let instance = axios.create();
    instance.defaults.headers.common['Authorization'] = USER_JWT_VALID;

    return instance.get('http://localhost:3000/api/private')
      .then((response) => {
        expect(response.data).to.be.an('object'); // response.data undefined
      }).catch((error) => {
        console.log('err ', error); //socket hang up
      });
  });
});

If I delete passport.authenticateand just send the json response, it works as expected.

, JWT .

RE

DB/ dev test. dev, , . , , "" ( ).

JWT, : (

, api - GET , . . , .

+4
1

, . GET- JWT .

, , , ( mongo db), - JWT. , , JWT .

, ( ). .

:

1) POST , JWT ( )

2) GET private auth JWT.

GET, passport.authenticate('jwt' .... , , .

, , JWT.

, , / .

0

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


All Articles