如何在 localhost 採用 https

在做 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值