Testing authenticated routes with JWT fails using

2019-07-25 18:11发布

问题:

I'm trying to test authenticated routes in Mocha but the user created in before or beforeEach hooks does not persist.

In test.js

const should = require('chai').should(),
    mongoose = require('mongoose'),
    request = require('supertest'),
    app = require('../../../../server'),
    agent = request.agent(app),
    AdminUser = require('../../../models/AdminUser');

var credentials = {
    username: 'admin',
    password: 'password'
};

var admin = new AdminUser(credentials);

describe('authenticated routes', function() {
     before(function (done) {
         admin.save(function (err) {
             if (err) done(err);

             agent.post('/api/authenticate')
             .send(credentials)
             .end(function (err, res) {
                 if (err) done(err);
                 jwtToken = res.body.token;
                 done();
             });
         });
     });

    it('should get content with 200', function (done) {
        agent.get('/api/content')
        .set('Authorization', 'JWT ' + jwtToken)
        .expect(200)
        .end((err, res) => {
            if (err) return done(err);
            done();
        });
    });

    after(function (done) {
        AdminUser.remove().exec();
        done();
    })
});

I have tried using beforeEach and cleaning up in afterEach, the initial post to /api/authenticate returns a 200 successfully, a token is received but when trying to authenticate with the token, it gets a 400. This is due to AdminUser not found.

In passport strategy, I have:

module.exports = function (passport) {
    passport.use(new JwtStrategy(opts, function(jwtPayload, done) {
        AdminUser.findOne({ username: jwtPayload.username }, function (err, user) {
            if (err) { return done(err); }
            if (!user) {
                return done(null, false, { message: 'Bad token.' });
            }
            return done(null, user);
        });
    }));
};

AdminUser is always null regardless of where I save the user. Only works when I nest the callbacks but that negates the use of before or beforeEach.

回答1:

You need to use Authorization header with the Bearer authentication scheme:

.set('Authorization', 'Bearer ' + jwtToken)