Home Web Front-end JS Tutorial Analysis of https use cases in Node.js

Analysis of https use cases in Node.js

May 24, 2018 am 09:53 AM
https javascript 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:

    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:

1

2

3

4

5

6

7

8

9

10

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.

1

2

mkdir cert

cd cert

Copy after login

2. Generate private key.

1

openssl genrsa -out chyingp-key.pem 2048

Copy after login

3. Generate a certificate signing request (csr means Certificate Signing Request).

1

2

3

4

5

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.

1

2

3

4

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:

1

2

3

4

5

6

7

8

9

10

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:

1

2

3

4

5

6

7

8

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 就行,再次运行代码,就可以愉快的返回页面了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// 例子:忽略安全警告

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的区别,可参考 这里 。

1

openssl x509 -in srca.cer -inform der -outform pem -out srca.cer.pem

Copy after login

3、修改node https的配置

修改后的代码如下,现在可以愉快的访问12306了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// 例子:将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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

What does the https workflow look like? What does the https workflow look like? Apr 07, 2024 am 09:27 AM

The https workflow includes steps such as client-initiated request, server response, SSL/TLS handshake, data transmission, and client-side rendering. Through these steps, the security and integrity of data during transmission can be ensured.

See all articles