Analysis of https use cases in Node.js

php中世界最好的语言
Release: 2018-05-24 09:53:12
Original
2188 people have browsed it

This time I will bring you an analysis of https usage cases inNode.js, what are theprecautionsfor 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:

    An introductory explanation of the https module through examples of the client and server.
  1. How to access websites with untrusted security certificates. (Take 12306 as an example)
  2. Due to limited space, this article cannot explain too much about the HTTPS protocol and related technical systems. If you have any questions, please leave a message to exchange.

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); });
Copy after login

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 certificate

1. Create a directory to store the certificate.

mkdir cert cd cert
Copy after login

2. Generate private key.

openssl genrsa -out chyingp-key.pem 2048
Copy after login

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"
Copy after login

4. Generate certificate.

openssl x509 \ -req -in chyingp-csr.pem \ -signkey chyingp-key.pem \ -out chyingp-cert.pem
Copy after login

HTTPS 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);
Copy after login

Since I do not have the domain name www.chyingp.com, I first configure the local host

127.0.0.1 www.chyingp.com

Start 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:

    Stop visiting: Fellow villagers who are anxious to grab tickets to go home for the New Year say they cannot accept it.
  1. Ignore the security warning and continue to visit: In most cases, the browser will allow it, but the security prompt will still be there.
  2. Import the CA root certificate of 12306: the browser obeys and thinks that access is safe. (Actually, there are still security prompts because the signature algorithm used by 12306 does not have enough security level)
Example: Triggering security restrictions

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); });
Copy after login

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 chain
at 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签名的证书还是不一样的。

类似在浏览器里访问,我们可以采取如下处理:

  1. 不建议:忽略安全警告,继续访问;

  2. 建议:将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); });
Copy after login

方法2:将12306的CA加入受信列表

这里包含3个步骤:

  1. 下载 12306 的CA证书

  2. 将der格式的CA证书,转成pem格式

  3. 修改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
Copy after login

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); });
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

设计模式的策略模式怎样在前端中使用

怎样使用JS+H5实现微信摇一摇

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!