使用Mocha + supertest +护照使用JWT测试经过身份验证的路由失败 [英] Testing authenticated routes with JWT fails using Mocha + supertest + passport

查看:115
本文介绍了使用Mocha + supertest +护照使用JWT测试经过身份验证的路由失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Mocha中测试经过身份验证的路由,但是在beforebeforeEach挂钩中创建的用户不能持久保存.

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

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();
    })
});

我尝试使用beforeEach并在afterEach中清理,到/api/authenticate的初始帖子成功返回了200,收到了令牌,但是当尝试使用令牌进行身份验证时,它得到了.这是由于找不到AdminUser.

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.

在护照策略中,我有:

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始终为null.仅当我嵌套回调时有效,但否定了beforebeforeEach的使用.

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.

推荐答案

您需要在 Bearer 身份验证方案中使用Authorization标头:

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

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

这篇关于使用Mocha + supertest +护照使用JWT测试经过身份验证的路由失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆