Ionic 4项目iOS端SSL Pinning失效问题求助
问题概述
使用@ionic-native/http + cordova-plugin-advanced-http实现SSL Pinning时,Android平台正常,iOS平台抛出证书验证错误:
NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “www.google.com.tr” which could put your confidential information at risk.
证书存放路径:src/assets/certificates(目录结构截图:
)
测试代码片段(app.component.ts):
this.http .setSSLCertMode("pinned") .then((response) => { console.log("SSL Pinning - Aktif GÖrünüyor"); }) .catch(() => { console.log("SSL Pinning - Başarısız"); }); this.http .get("https://www.google.com/", {}, {}) .catch((error) => { const showMaintenanceMessage = this.modalController.create( Maintenance, { message: "Sertifikanız Doğrulanamadı", }, { showBackdrop: false, enableBackdropDismiss: false, } ); showMaintenanceMessage.present(); this.platform.exitApp(); }); // SSL PINNING END //
核心原因与解决方案
1. 域名跳转导致证书不匹配
错误信息中显示验证的是www.google.com.tr,但代码请求的是www.google.com——Google会根据iOS设备所在地区自动跳转到国别域名,而你仅配置了www.google.com的证书,导致跳转后的域名证书验证失败。
- 解决步骤:
- 抓取iOS环境下
www.google.com实际跳转目标(如www.google.com.tr)的根/中间证书 - 将该证书添加到
src/assets/certificates目录 - 确保插件配置包含所有需验证的证书
- 抓取iOS环境下
2. iOS证书格式与配置错误
cordova-plugin-advanced-http在iOS端对证书要求更严格:
- 必须使用PEM格式证书,文件后缀为
.pem(禁止DER等其他格式) - 需使用根证书或中间证书,不能用服务器叶子证书
- 在
config.xml中明确配置证书路径:<platform name="ios"> <preference name="AdvancedHttpCertificatePath" value="assets/certificates/" /> <preference name="AdvancedHttpCertificatePinMode" value="pinned" /> </platform>
3. 异步时序问题
当前代码中setSSLCertMode(异步操作)与get请求并行执行,iOS下异步时序敏感度更高,可能导致SSL Pinning配置未生效就发起请求。修改代码等待配置完成后再请求:
this.http .setSSLCertMode("pinned") .then(() => { console.log("SSL Pinning - Aktif GÖrünüyor"); // 配置生效后发起请求 return this.http.get("https://www.google.com/", {}, {}); }) .catch((error) => { const showMaintenanceMessage = this.modalController.create( Maintenance, { message: "Sertifikanız Doğrulanamadı" }, { showBackdrop: false, enableBackdropDismiss: false } ); showMaintenanceMessage.present(); this.platform.exitApp(); });
4. 插件版本兼容性
Ionic 4需匹配@ionic-native/http 5.x版本,同时确保cordova-plugin-advanced-http为最新稳定版:
# 卸载旧插件 cordova plugin rm cordova-plugin-advanced-http # 安装最新版 cordova plugin add cordova-plugin-advanced-http@latest
5. iOS ATS配置补充
在config.xml中添加ATS例外,覆盖跳转后的子域名:
<platform name="ios"> <config-file parent="NSAppTransportSecurity" target="*-Info.plist"> <dict> <key>NSAllowsArbitraryLoads</key> <false/> <key>NSExceptionDomains</key> <dict> <key>google.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <false/> </dict> <key>google.com.tr</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <false/> </dict> </dict> </dict> </config-file> </platform>
内容的提问来源于stack exchange,提问作者Taha Ateş

