如何解决Node.js(NestJS)TLS连接中的ERR_TLS_CERT_ALTNAME_INVALID错误?
Node.js TLS连接报错:ERR_TLS_CERT_ALTNAME_INVALID 问题排查与解决
我在NestJS中使用tls.connect()建立TLS连接时,遇到如下错误:
Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames
同事使用相同证书、IP地址和端口,在Android Studio的Java环境中通过Keystore工具可成功建立连接,说明证书本身有效,问题为Node.js环境特有。
补充信息:
- 要求连接使用TLSv1.2,但服务器实际运行在TLSv1.3,强制指定TLSv1.2后仍报错
- Node.js版本:14.20.0
- NestJS版本:最新版
代码示例
const fs = require('fs'); const tls = require('tls'); const options = { cert: fs.readFileSync('certssl/cert.crt'), host: '196.xxx.xx.xx', port: 443, rejectUnauthorized: true, maxVersion: 'TLSv1.2', }; const connectionOperation = tls.connect(options, () => { if (connectionOperation.authorized) { console.log('Connection authorized'); connectionOperation.write(hexString); } else { console.log('Connection not authorized'); console.log(connectionOperation.authorizationError); } });
日志信息
Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames: IP: 196.xxx.xx.xx is not in the cert's list: at new NodeError (internal/errors.js:322:7) at Object.checkServerIdentity (tls.js:347:12) at TLSSocket.onConnectSecure (_tls_wrap.js:1525:27) at TLSSocket.emit (events.js:400:28) at TLSSocket._finishInit (_tls_wrap.js:937:8) at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12)
问题原因
Node.js(v14及以上)严格遵循RFC标准,仅认可证书Subject Alternative Name(SAN)字段中的IP地址条目;而Java允许直接用IP匹配证书的Common Name(CN)字段,这就是两者行为差异的核心原因。
解决方法
方法1:修改证书添加IP到SAN字段(推荐生产环境)
联系证书运维或颁发方,将目标IP196.xxx.xx.xx添加到证书的SAN扩展字段中,重新生成证书后替换现有cert.crt即可正常连接。
方法2:自定义证书校验逻辑(临时测试方案)
若暂时无法修改证书,可通过自定义checkServerIdentity函数跳过IP匹配校验(会降低安全性,仅用于测试):
const options = { cert: fs.readFileSync('certssl/cert.crt'), host: '196.xxx.xx.xx', port: 443, rejectUnauthorized: true, maxVersion: 'TLSv1.2', // 自定义校验逻辑,跳过IP与SAN的匹配检查 checkServerIdentity: (hostname, cert) => { // 可保留证书有效期、颁发机构等其他校验逻辑 return undefined; // 返回undefined表示校验通过 } };
方法3:使用域名连接
如果服务器绑定了已在证书SAN/CN字段中的域名,将options.host替换为该域名,Node.js会自动匹配证书中的域名条目。
额外注意事项
- Node.js 14.x对TLS校验比旧版本更严格,需确保证书配置符合RFC标准
- TLS版本与证书SAN校验逻辑无关,强制指定TLSv1.2不会解决该报错
内容的提问来源于stack exchange,提问作者skander lassoued
相关产品推荐
相关产品推荐

