Home >Web Front-end >JS Tutorial >Analysis of https use cases in Node.js
This time I will bring you an analysis of https usage cases in Node.js, what are the precautions for using https in Node.js, the following is a practical case, let’s take a look one time.
ModuleOverview
The importance of this module basically does not need to be emphasized. Today, when network security issues are becoming increasingly serious, it is an inevitable trend for websites to adopt HTTPS. In nodejs, the https module is provided to complete HTTPS related functions. Judging from the official documentation, it is very similar to the usage of the http module.
This article mainly contains two parts:
Client exampleThe usage is very similar to the http module, except that the requested address is https protocol. The code is as follows:
var https = require('https'); https.get('https://www.baidu.com', function(res){ console.log('status code: ' + res.statusCode); console.log('headers: ' + res.headers); res.on('data', function(data){ process.stdout.write(data); }); }).on('error', function(err){ console.error(err); });
Server exampleTo provide HTTPS services to the outside world, an HTTPS certificate is required. If you already have an HTTPS certificate, you can skip the certificate generation step. If not, you can refer to the following steps
Generate a certificate1. Create a directory to store the certificate.
mkdir cert cd cert
2. Generate private key.
openssl genrsa -out chyingp-key.pem 2048
3. Generate a certificate signing request (csr means Certificate Signing Request).
openssl req -new \ -sha256 -key chyingp-key.key.pem \ -out chyingp-csr.pem \ -subj "/C=CN/ST=Guandong/L=Shenzhen/O=YH Inc/CN=www.chyingp.com"
4. Generate certificate.
openssl x509 \ -req -in chyingp-csr.pem \ -signkey chyingp-key.pem \ -out chyingp-cert.pemHTTPS server
The code is as follows:
var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('./cert/chyingp-key.pem'), // 私钥 cert: fs.readFileSync('./cert/chyingp-cert.pem') // 证书 }; var server = https.createServer(options, function(req, res){ res.end('这是来自HTTPS服务器的返回'); }); server.listen(3000);
Since I do not have the domain name www.chyingp.com, I first configure the local host
127.0.0.1 www.chyingp.comStart the service and visit http://www.chyingp.com:3000 in the browser. Note that the browser will prompt you that the certificate is unreliable, just click Trust and continue visiting.
Advanced example: accessing a website with an untrusted security certificateHere is our favorite 12306 as an example. When we access the 12306 ticket purchase page https://kyfw.12306.cn/otn/regist/init through the browser, chrome will prevent us from accessing it. This is because the certificate of 12306 is issued by itself and chrome cannot confirm it. His safety.
To deal with this situation, the following methods can be used:
Similarly, You will also encounter the same problem when making requests through node https client. Let's do an experiment, the code is as follows:
var https = require('https'); https.get('https://kyfw.12306.cn/otn/regist/init', function(res){ res.on('data', function(data){ process.stdout.write(data); }); }).on('error', function(err){ console.error(err); });
Run the above code and get the following error message, which means that the security certificate is unreliable and continued access is denied.
{ Error: self signed certificate in certificate chainat Error (native)at TLSSocket.
(_tls_wrap.js:1055:38)
at emitNone (events.js:86:13)
at TLSSocket.emit (events.js:185:7)
at TLSSocket._finishInit (_tls_wrap.js:580:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:412:38) code: 'SELF_SIGNED_CERT_IN_CHAIN' }
ps:个人认为这里的错误提示有点误导人,12306网站的证书并不是自签名的,只是对证书签名的CA是12306自家的,不在可信列表里而已。自签名证书,跟自己CA签名的证书还是不一样的。
类似在浏览器里访问,我们可以采取如下处理:
不建议:忽略安全警告,继续访问;
建议:将12306的CA加入受信列表;
方法1:忽略安全警告,继续访问
非常简单,将 rejectUnauthorized 设置为 false 就行,再次运行代码,就可以愉快的返回页面了。
// 例子:忽略安全警告 var https = require('https'); var fs = require('fs'); var options = { hostname: 'kyfw.12306.cn', path: '/otn/leftTicket/init', rejectUnauthorized: false // 忽略安全警告 }; var req = https.get(options, function(res){ res.pipe(process.stdout); }); req.on('error', function(err){ console.error(err.code); });
方法2:将12306的CA加入受信列表
这里包含3个步骤:
下载 12306 的CA证书
将der格式的CA证书,转成pem格式
修改node https的配置
1、下载 12306 的CA证书
在12306的官网上,提供了CA证书的 下载地址 ,将它保存到本地,命名为 srca.cer。
2、将der格式的CA证书,转成pem格式
https初始化client时,提供了 ca 这个配置项,可以将 12306 的CA证书添加进去。当你访问 12306 的网站时,client就会用ca配置项里的 ca 证书,对当前的证书进行校验,于是就校验通过了。
需要注意的是,ca 配置项只支持 pem 格式,而从12306官网下载的是der格式的。需要转换下格式才能用。关于 pem、der的区别,可参考 这里 。
openssl x509 -in srca.cer -inform der -outform pem -out srca.cer.pem
3、修改node https的配置
修改后的代码如下,现在可以愉快的访问12306了。
// 例子:将12306的CA证书,加入我们的信任列表里 var https = require('https'); var fs = require('fs'); var ca = fs.readFileSync('./srca.cer.pem'); var options = { hostname: 'kyfw.12306.cn', path: '/otn/leftTicket/init', ca: [ ca ] }; var req = https.get(options, function(res){ res.pipe(process.stdout); }); req.on('error', function(err){ console.error(err.code); });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Analysis of https use cases in Node.js. For more information, please follow other related articles on the PHP Chinese website!