如何为Node.js创建一个自签名的HTTPS证书来测试本地的应用程序

641 阅读2分钟

如何为Node.js创建一个自签名的HTTPS证书来测试本地的应用程序

为了能够从localhost提供HTTPS网站,你需要创建一个自签名证书。

一个自签名的证书足以建立一个安全的HTTPS连接,用于开发目的。尽管浏览器会抱怨说该证书是自签的(因此不被信任)。

要创建证书,你必须在你的系统上安装OpenSSL

你可能已经安装了它,只需在你的终端输入openssl

如果没有,在Mac上你可以用brew install openssl (如果你使用Homebrew)来安装它。否则,在谷歌上搜索 "如何在"上安装openssl"。

一旦OpenSSL被安装,运行这个命令。

openssl req -nodes -new -x509 -keyout server.key -out server.cert

你会被提示回答几个问题。首先是国家名称。

Generating a 1024 bit RSA private key
...........++++++
.........++++++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:

然后是你的州或省。

State or Province Name (full name) [Some-State]:

你的城市。

Locality Name (eg, city) []:

...和你的组织名称。

Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:

你可以让这些都是空的。

只要记得将其设置为localhost:

Common Name (e.g. server FQDN or YOUR name) []: localhost

...并添加你的电子邮件地址。

这就是了!现在你在运行原始命令的文件夹里有两个文件。

  • server.cert 是自签名的证书文件
  • server.key 是证书的私钥

建立HTTPS连接将需要这两个文件,根据你将如何设置你的服务器,使用它们的过程将有所不同。

这些文件需要放在一个应用程序可以到达的地方,然后你需要配置服务器来使用它们。

这是一个使用https 核心模块和Express的例子。

const https = require('https')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({}, app).listen(3000, () => {
  console.log('Listening...')
})

在没有添加证书的情况下,如果我连接到https://localhost:3000 ,浏览器会显示这个结果。

without-cert

在添加了证书的情况下。

const fs = require('fs')

//...

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(3000, () => {
  console.log('Listening...')
})

Chrome会告诉我们证书无效(因为它是自签的),并要求我们在继续之前进行确认(不过,HTTPS连接仍然可以工作)。

with-cert