【问题标题】:How to use mutual SSL with test framework Mocha/Chai(chai-http) on a Node.js application如何在 Node.js 应用程序上使用相互 SSL 和测试框架 Mocha/Chai(chai-http)
【发布时间】:2020-01-17 10:05:20
【问题描述】:

我正在开发一个使用相互 SSL 身份验证的应用程序,我想编写自动化测试来评估功能。

我已经实现了服务器,我可以使用 Postman 进行测试。这篇文章运行良好。

在我的摩卡测试中,我写了这个请求:

chai.request(getServer())
    .post('/users')
    .ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
    .cert(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
    .key(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
    .send(userToCreate)
    .end((error, response) => {
         if (error !== null) {
             reject(`User creation error : ${JSON.stringify(error)}`);
         } else if (response.status !== 201) {
             reject(`User creation failed : ${JSON.stringify(response.status)}`);
         } else {
             resolve(response.body);
         }
    });

但此请求不会向服务器发送任何证书:

  • request.socket.authorized = 未定义

我尝试使用 HTTPS 代理:

let agent = new Agent({
    ca: fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'),
    key: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'),
    cert: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt.pem'), 'utf-8')
});
chai.request(getServer())
    .post('/users')
    .agent(agent)
    .send(userToCreate)
    .end((error, response) => {
         if (error !== null) {
             reject(`User creation error : ${JSON.stringify(error)}`);
         } else if (response.status !== 201) {
             reject(`User creation failed : ${JSON.stringify(response.status)}`);
         } else {
             resolve(response.body);
         }
    });

但此请求不会向服务器发送任何证书:

  • request.socket.authorized = 未定义
  • 我在 mocha 测试中遇到 ERR_INVALID_PROTOCOL 异常

有人可以帮帮我吗?

【问题讨论】:

    标签: node.js ssl mocha.js chai chai-http


    【解决方案1】:

    我终于通过直接使用superagent而不是chai-http解决了这个问题。尽管 chai-http 使用了 superagent,但看起来实现错过了方法 ca、cert 和 key。所以下面的语法为我解决了这个问题:

    superAgent
        .post('http:/localhost/users')
        .ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
        .cert(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
        .key(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
        .send(sentBody)
        .end((error, response) => {
            if (error !== null) {
                reject(`User creation error : ${JSON.stringify(error)});
            } else if (response.status !== 201) {
                reject(`User creation failed : ${JSON.stringify(response.status)});
            } else {
                resolve(response.body);
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2020-10-11
      • 2017-06-09
      • 2019-02-15
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多