在Express中测试受保护的路由时如何使用jwt进行身份验证

时间:2020-07-31 10:38:48

标签: node.js express jwt mocha supertest

我正在尝试使用supertest以快速方式测试受保护的路由。以下代码给我一个403错误,因此我无法正确运行任何测试。

gameRouter.js-受保护的路线:

router.post(
    '/posts/:id/comments/add-comment',
    verifyToken,
    controller.addCommentToPost
);

verifyToken函数:

exports.verifyToken = (req, res, next) => {
    try {
        if (isDataNullOrUndefined(req.headers.authorization)) {
            throwAPIError(401, 'ERR_MISSING_TOKEN', 'Missing token');
        }
        // FORMATTED AS - "BEARER TOKEN.IS.HERE"
        const token = req.headers.authorization.split(' ')[1];
        const decodedToken = jwt.verify(token, jwtConfig.secret);
        const userId = decodedToken.userId;

        if (!userId || (req.body.userId && req.body.userId !== userId)) {
            throwAPIError(403, 'ERR_INVALID_TOKEN', 'Invalid token');
        } else {
            next();
        }
    } catch (err) {
        const error = createErrorData(err);
        res.status(error.code).json(error.error);
    }
};

路线测试:

const supertest = require('supertest');
const { describe, it } = require('mocha');

const app = require('../app');

const request = supertest(app);

let token;
describe('Game Tests', () => {
    describe('Add a comment to a post', () => {
        before((done) => {
            request
                .post('/api/users/login')
                .send({
                    email: 'correct@email.com',
                    password: 'SomeGreatPassword',
                })
                .end((err, res) => {
                    token = res.body.token;
                    return done();
                });
        });

        it('should not allow a comment to be made on a non found post', (done) => {
            request
                .post('api/games/posts/-1/comments/add-comment')
                .auth(token, { type: 'Bearer' })
                .expect(404, done);
        });
    });
});

1 个答案:

答案 0 :(得分:0)

请尝试一下,让我知道您是否遇到相同的问题。

服务器-您的服务器(即登台/发布)
url-您的目标块/ url

import request from 'supertest';
import server from 'path/to/your/server';  // if you are checking in localhost
const server = https://urdeployedurl.com; // if you are checking in deployed environment 
async authValidation() { 
const token = 'your token'
const body = 'your data'
const authVerification = await request(server)
      .post(url)
      .set({ Authorization: 'bearer ' + token, 'Content-Type': 'application/json' })
      .send(JSON.stringify(body));
console.log(authVerification.status)
}