React Native WebView渲染时出现SSL证书信任问题求助
解决React Native Webview SSL证书不被信任的问题
针对你遇到的SSL error: The certificate authority is not trusted错误,分iOS和Android平台给出具体解决方案,注意测试环境临时方案不可用于生产环境:
iOS 平台
方案1:测试环境临时放宽ATS限制
编辑项目根目录下的ios/[你的项目名]/Info.plist,添加或修改NSAppTransportSecurity配置:
<key>NSAppTransportSecurity</key> <dict> <!-- 全局允许(仅测试用,上线必须删除) --> <key>NSAllowsArbitraryLoads</key> <true/> <!-- 更安全的特定域名配置(推荐测试用) --> <key>NSExceptionDomains</key> <dict> <key>your-target-domain.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.2</string> </dict> </dict> </dict>
方案2:添加自定义CA证书(生产环境可用)
- 将CA证书文件(
.cer格式)拖入Xcode项目,勾选对应项目目标的"Add to targets"选项; - 在
Info.plist的NSExceptionDomains中配置目标域名,指定信任该CA证书:
<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>your-target-domain.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <false/> <key>NSExceptionCertificate</key> <array> <string>your-ca-cert.cer</string> </array> </dict> </dict> </dict>
Android 平台
方案1:测试环境绕过SSL验证
通过react-native-webview的onReceivedSslError回调处理,仅在开发模式下执行:
import WebView from 'react-native-webview'; // 组件内使用 <WebView source={{ uri: 'https://your-target-domain.com' }} onReceivedSslError={(event, handler) => { if (__DEV__) { handler.proceed(); // 仅开发环境使用,上线必须移除 } else { handler.cancel(); } }} />
方案2:添加自定义CA证书(生产环境可用)
- 将CA证书文件(
.crt格式)放入android/app/src/main/res/raw目录; - 创建自定义TrustManager加载证书,配置WebView的SSLContext:
// 自定义TrustManager示例(需在Android原生代码中实现) import android.content.Context; import android.content.res.Resources; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; public class CustomTrustManager { public static SSLContext getSSLContext(Context context) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Resources res = context.getResources(); InputStream caInput = res.openRawResource(R.raw.your_ca_cert); X509Certificate ca; try { ca = (X509Certificate) cf.generateCertificate(caInput); } finally { caInput.close(); } String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); return sslContext; } }
之后在WebView初始化时设置该SSLContext即可。
内容的提问来源于stack exchange,提问作者Paras Jain
相关产品推荐
相关产品推荐

