如何生成自签证书并信任系统?

解读

在前端工程化场景里,本地 HTTPS 开发服务器(如 Browsersync、webpack-dev-server、Vite)已成标配。Gulp 通过 gulp-connect、browser-sync 等插件启动服务时,若未提供合法证书,浏览器会拦截请求,导致热更新、Service Worker、WebRTC 等特性无法调试。因此,“生成自签证书并信任系统” 是考察候选人能否独立搭建“零警告”本地开发环境的关键环节。面试官期望听到:

  1. 用 OpenSSL 生成符合 RFC 5280 的证书;
  2. 把证书写入 系统受信根存储,消除浏览器红锁;
  3. 通过 Gulp 任务链把证书路径注入 dev-server,实现一键 gulp serve --https;
  4. 兼顾 Windows 企业版、macOS、Ubuntu 三大国内主流开发机的差异命令;
  5. 说明潜在风险与合规边界,避免“给生产域名签假证书”之类的误操作。

知识点

  • X.509 v3 结构:Subject、Issuer、SAN(Subject Alternative Name)决定浏览器是否报 NET::ERR_CERT_COMMON_NAME_INVALID。
  • KeyUsage & ExtendedKeyUsage:必须包含 digitalSignature + keyEncipherment 与 serverAuth,否则 Chrome 提示 CERT_WEAK_KEY。
  • OpenSSL 配置文件:国内镜像源下载的 OpenSSL 常缺 v3_ca 段,需手动追加 subjectAltName=DNS:localhost,IP:127.0.0.1 防止证书被标记为无效。
  • 系统信任存储:
    • Windows:证书写入 “受信任的根证书颁发机构” 存储区,需管理员 PowerShell Import-Certificate;
    • macOS:钥匙串访问中设为 “始终信任”,或用 sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain;
    • Ubuntu/Debian:复制 .crt 到 /usr/local/share/ca-certificates/ 后执行 sudo update-ca-certificates。
  • Gulp 集成:借助 gulp-connect 的 httpsOptions 字段或 browser-sync 的 https: { key, cert } 直接引用本地 PEM 文件;通过 yargs 解析 CLI 参数 --https 动态切换协议。
  • 证书有效期:自签证书默认 365 天,国内部分公司安全软件会强制 ≤825 天,需在 -days 参数中显式控制。
  • 合规提示:自签证书仅限 localhost、127.0.0.1、*.test 等保留域,禁止给公网域名签发,否则违反《电子认证服务管理办法》。

答案

下面给出一条可在 Windows PowerShell(管理员)、macOS、Ubuntu 上直接落地的命令序列,并配套 Gulp 任务示例。假设项目根目录已创建 certs 文件夹。

  1. 创建 OpenSSL 配置文件 certs/localhost.cnf
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no

[req_distinguished_name]
CN = localhost

[v3_req]
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = *.localhost
IP.1 = 127.0.0.1
IP.2 = ::1
  1. 生成私钥与证书
openssl req -x509 -newkey rsa:2048 -nodes \
  -keyout certs/localhost.key -out certs/localhost.crt \
  -days 365 -config certs/localhost.cnf -sha256
  1. 信任系统(任选其一)
  • Windows:
Import-Certificate -FilePath "$PWD/certs/localhost.crt" -CertStoreLocation "Cert:\LocalMachine\Root"
  • macOS:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain certs/localhost.crt
  • Ubuntu:
sudo cp certs/localhost.crt /usr/local/share/ca-certificates/localhost.crt
sudo update-ca-certificates
  1. Gulp 任务注入证书
// gulpfile.js
const { src, dest, watch, series } = require('gulp');
const connect = require('gulp-connect');
const fs = require('fs');
const yargs = require('yargs');

const httpsFlag = yargs.argv.https;

function serve(done) {
  const options = {
    root: 'dist',
    port: 3000,
    livereload: true
  };
  if (httpsFlag) {
    options.https = {
      key: fs.readFileSync('certs/localhost.key'),
      cert: fs.readFileSync('certs/localhost.crt')
    };
  }
  connect.server(options);
  done();
}

exports.serve = serve;
  1. 启动
# 普通 HTTP
gulp serve
# 可信 HTTPS
gulp serve --https

浏览器首次访问 https://localhost:3000 将直接显示安全锁,无警告。

拓展思考

  1. 多域名开发:微前端场景下,本地需同时调试 a.localhost、b.localhost,可在 alt_names 继续追加 DNS 条目,一条证书覆盖全部子域,避免重复签发。
  2. 证书热更新:把上述 OpenSSL 命令封装成 gulp cert 任务,监听 certs/localhost.cnf 变动后自动重签,再触发 browser-sync.reload,实现“改配置→立即信任→立即生效”的闭环。
  3. 团队共享:将 localhost.crt 提交到仓库 certs/ 目录,并在 README.md 写明一键信任脚本,新人克隆项目后 30 秒完成环境搭建,显著提升 onboarding 效率。
  4. CI 镜像:GitHub Actions / 阿里云 Flow 的 Linux 容器默认不信任自签证书,可在 yaml 里加 sudo cp certs/localhost.crt /usr/local/share/ca-certificates && sudo update-ca-certificates,保证 e2e 测试在 HTTPS 下运行。
  5. 安全风险:若私钥 localhost.key 意外泄露,攻击者结合 DNS 劫持可伪造 localhost 服务,因此要在 .gitignore 中排除 *.key,并通过 pre-commit 钩子强制检测。