如何使用 supertest、passport 和 JEST 在 cookie 中使用 jwt 测试身份验证

How to test authentication with jwt inside a cookie with supertest, passport, and JEST

嘿伙计们,我目前正在尝试做一些类似于 posted 在这里的事情: How to authenticate Supertest requests with Passport?

因为我想测试其他需要身份验证但还需要传入 jwt 的端点。现在,我在 POSTMAN 和浏览器上对其进行了测试,它似乎工作正常,但我的测试用例不断出现故障。我有一个登录 POST 路由,设置如下:

AccountService.js

// Login POST route
  router.post('/account_service/login', (req, res, next) => {
    passport.authenticate('local-login', (err, user, info) => {
      try {
        if (err) {
          const error = new Error('An Error occurred: Cannot find user');
          return next(error);
        } else if (!user) {
          return res.redirect('/account_service/login');
        }
        req.login(user, { session: false }, (error) => {
          if (error) {
            return next(error);
          }
          const email = req.body.email;
          const role = req.user[0].role;
          const id = req.user[0].id;

          const user = {
            email: email,
            role: role,
            id: id
          };
          const accessToken = jwt.sign(user, config.ACCESS_TOKEN_SECRET, {
            expiresIn: 28800 // expires in 8 hours
          });
          const cookie = req.cookies.cookieName;
          if (cookie === undefined) {
            // set a new cookie
            console.log('setting new cookie');
            res.cookie('jwt', accessToken, { maxAge: 900000, httpOnly: true });
            res.send({ token: accessToken });
          } else {
            // cookie was already present
            console.log('cookie exists', cookie);
          }
          res.redirect('/account_service/profile');
        });
      } catch (error) {
        return next(error);
      }
    })(req, res, next);
  });

用户通过身份验证后,我将一个 JSON 网络令牌分配给用户并将其放入 cookie 中,以便将其存储在 headers 中以供授权请求使用。这是一个例子:

AccountService.js

// Get all users
  router.get('/account_service/all_users', passport.authenticate('jwt', { session: false }), (req, res, next) => {
    const sql = 'select * from user';
    const params = [];
    db.all(sql, params, (err, rows) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({
        message: 'success',
        data: rows
      });
    });
  });

我使用 passport.authenticate 来确保 jwt 有效。此 GET 请求仅在我使用管理员用户帐户登录后有效。

在我的护照文件中,我的设置如下:

passport.js

const LocalStrategy = require('passport-local').Strategy;
const db = require('../database.js');
const bcrypt = require('bcrypt');
const config = require('../config/config.js');
const JwtStrategy = require('passport-jwt').Strategy;

const cookieExtractor = function (req) {
  var token = null;
  if (req && req.cookies) token = req.cookies.jwt;
  return token;
};

module.exports = function (passport) {
  passport.serializeUser(function (user, done) {
    done(null, user);
  });
  passport.deserializeUser(function (user, done) {
    done(null, user);
  });
  passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  }, (req, email, password, done) => {
    try {
      const sql = `select * from user WHERE email = "${email}"`;
      const params = [];
      db.all(sql, params, (err, row) => {
        if (err) {
          return done(err);
        }
        if (!row.length || !bcrypt.compareSync(password, row[0].password)) {
          return done(null, false, req.flash('loginMessage', 'Inavalid username/password combination. Please try again.'));
        }
        return done(null, row);
      });
    } catch (error) {
      return done(error);
    }
  }));

  const opts = {};
  opts.jwtFromRequest = cookieExtractor; // check token in cookie
  opts.secretOrKey = config.ACCESS_TOKEN_SECRET;
  // eslint-disable-next-line camelcase
  passport.use(new JwtStrategy(opts, function (jwtPayload, done) {
    try {
      const sql = `select * from user WHERE email = "${jwtPayload.email}"`;
      const params = [];
      db.all(sql, params, (err, row) => {
        if (err) {
          return done(err);
        }
        if (!row.length || !bcrypt.compareSync('admin', jwtPayload.role)) {
          return done(null, false, { message: '403 Forbidden' });
        }
        return done(null, row);
      });
    } catch (error) {
      return done(error);
    }
  }));
};

这是我的测试用例崩溃时感到困惑的地方。我试图在我的测试用例之前登录以允许我的其他测试用例 运行 但我最终收到 401 错误。这是我的测试用例:

accountservice.test.js

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

describe('Account Service', () => {
  let server;
  let request;

  beforeAll((done) => {
    server = http.createServer(app);
    server.listen(done);
    request = supertest.agent(server);
    request.post('/account_service/login')
      .send({ email: 'admin@example.com', password: 'admin' })
      .end(function (err, res) {
        if (err) {
          return done(err);
        }
        console.log(res);
        done();
      });
  });

  afterAll((done) => {
    server.close(done);
  });

  it('Test request all users endpoint | GET request', async done => {
    const response = await request.get('/account_service/all_users');
    expect(response.status).toBe(200);
    expect(response.body.message).toBe('success');
    expect(response.body.data.length).toBe(3);
    done();
  });
});

但是我的测试用例失败了,因为当它期望 200 成功代码时出现 401 错误。

我尝试想办法在登录调用后从 cookie 中提取 jwt,这样我就可以为 /account_service/all_users GET 请求代码设置 headers,但无法找到使用超测的方式。我看到这个 post: Testing authenticated routes with JWT fails using Mocha + supertest + passport 但看到它从 body.

获取令牌

在弄乱我的代码后,我最终遇到了 in-memory 存储和 运行 异步 db.run 函数的问题,这些函数每次我 运行 我的服务器都会调用.所以我使用了一个文件来存储我的数据并再次 运行 我的测试,它最终成功了!

错误代码如下:

const sqlite3 = require('sqlite3').verbose();
const md5 = require('md5');

const DBSOURCE = ':memory:';

const db = new sqlite3.Database(DBSOURCE, (err) => {
  if (err) {
    // Cannot open database
    console.error(err.message);
    throw err;
  } else {
    db.run(`CREATE TABLE user (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text, 
        email text UNIQUE, 
        password text, 
        status text,
        comments text, 
        photos text,
        CONSTRAINT email_unique UNIQUE (email)
        )`,
    (err) => {
      if (err) {
        // Table already created
        console.log('Table already created');
      } else {
        // Table just created, creating some rows
        const insert = 'INSERT INTO user (name, email, password, status, comments, photos) VALUES (?,?,?,?,?,?)';
        db.run(insert, ['user_delete', 'user_delete@example.com', md5('admin123456'), 'pending_deleted', 'comment1,comment2', 'https://giphy.com/gifs/9jumpin-wow-nice-well-done-xT77XWum9yH7zNkFW0']);
        db.run(insert, ['user_no_delete', 'user@example.com', md5('user123456'), 'active', 'comment1', 'https://giphy.com/gifs/cartoon-we-bare-bears-wbb-NeijdlusjcduU']);
        db.run(insert, ['mikey', 'mikey@example.com', md5('mikey123'), 'pending_deleted', 'comment1', 'https://giphy.com/gifs/wwe-shocked-vince-mcmahon-gdKAVlnm3bmKI']);
      }
    });
  }
});

module.exports = db;

我只是将这些数据存储在一个文件中并使用了以下代码:

const sqlite3 = require('sqlite3').verbose();
const DBSOURCE = 'mockdb.sqlite';

// Data inserted inside file
/*
db.run(insert, ['user_delete', 'user_delete@example.com', bcrypt.hashSync('admin123456', saltRounds), 'pending_deleted', 'comment1,comment2', 'https://giphy.com/gifs/9jumpin-wow-nice-well-done-xT77XWum9yH7zNkFW0', bcrypt.hashSync('user', saltRounds)]);
db.run(insert, ['user_no_delete', 'user@example.com', bcrypt.hashSync('user123456', saltRounds), 'active', 'comment1', 'https://giphy.com/gifs/cartoon-we-bare-bears-wbb-NeijdlusjcduU', bcrypt.hashSync('user', saltRounds)]);
db.run(insert, ['mikey', 'mikey@example.com', bcrypt.hashSync('mikey123', saltRounds), 'pending_deleted', 'comment1', 'https://giphy.com/gifs/wwe-shocked-vince-mcmahon-gdKAVlnm3bmKI', bcrypt.hashSync('user', saltRounds)]);
db.run(insert, ['admin', 'admin@example.com', bcrypt.hashSync('admin', saltRounds), 'active', 'admincomments', 'adminphoto', bcrypt.hashSync('admin', saltRounds)]);
  console.log('last hit in database');
});
*/

const db = new sqlite3.Database(DBSOURCE, (err) => {
  if (err) {
    // Cannot open database
    console.error(err.message);
    throw err;
  }
  console.log('Connection successful!');
});

module.exports = db;

我也最终使用了 supertest.agent。

const app = require('../../app');
const supertest = require('supertest');
const http = require('http');
const db = require('../../database/database.js');

describe('Account Service', () => {
  let server;
  let request;
  // Find cookie management option.
  beforeAll(async (done) => {
    server = http.createServer(app);
    server.listen(done);
    request = supertest.agent(server);
    done();
  });

它最终起作用并成功解决了我的问题!