在做 webrtc 時,要求必須是 https。那麼如何在本地服務器上啟用 https 呢?
參考 How to get HTTPS working on your local development environment in 5 minutes,下面是在 mac 上給 express 支持 https 的過程。
ssl 證書採用 openssl 生成,最終我們將得到兩個文件:
- server.key
- server.crt
將這兩個文件用於 express server 就可以了。
a. 生成根證書
根證書用於後面生成針對特定域名的證書。
生成一個 RSA-2048 key:
$ openssl genrsa -des3 -out rootCA.key 2048
使用該 key 生成證書:
$ openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
b. 在系統中信任該根證書
在 mac 中,打開 Keychain access,System -> File -> Import Items,選擇 rootCA.pem。
這時,該證書會有一個紅叉。
雙擊,在 Trust 中選中 Always Trust,完成。
c. 生成域名證書
1). 新建兩個文件
server.csr.cnf
[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
[dn]
C=US
ST=RandomState
L=RandomCity
O=RandomOrganization
OU=RandomOrganizationUnit
emailAddress=hello@example.com
CN = localhost
v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
2). 生成 server.key
用 1) 中的 server.csr.cnf 生成 server.key:
$ openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server.csr.cnf )
3). 生成證書 server.crt
這一步將使用前面保存的 v3.ext:
$ openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 -sha256 -extfile v3.ext
d. 使用 ssl
const path = require('path')
const express = require('express')
const fs = require('fs')
const https = require('https')
var certOptions = {
key: fs.readFileSync(path.resolve('cert/server.key')),
cert: fs.readFileSync(path.resolve('cert/server.crt'))
}
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
const server = https.createServer(certOptions, app).listen(4433)
運行服務器 node app.js
,打開瀏覽器 https://localhost:4433
,將看到服務器返回結果 hell world