繁体   English   中英

如何在 Node.js 应用程序上使用相互 SSL 和测试框架 Mocha/Chai(chai-http)

[英]How to use mutual SSL with test framework Mocha/Chai(chai-http) on a Node.js application

我正在开发一个使用相互 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 异常

有人可以帮我吗?

我终于通过直接使用 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);
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM