You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

M1芯片MacOS环境下React Native调用自签名证书API的问题求助

React Native Axios调用自签名证书API:iOS崩溃、Android网络错误解决方案

我帮你梳理下这个问题的解决方案,自签名证书在React Native中确实需要针对iOS和Android分别配置,结合你的情况,我们一步步来解决:

核心原因

自签名证书默认不被iOS/Android系统信任,加上React Native的网络层(Axios默认依赖XMLHttpRequest)没有默认处理这类证书,导致Android触发网络错误、iOS直接崩溃。我们需要通过**SSL Pinning(证书固定)**或原生层信任配置来解决。


第一步:准备证书文件

先从你的服务器导出自签名证书(格式选.cer,DER编码),然后放到React Native项目的指定目录中(比如项目根目录下新建certificates文件夹)。


第二步:配置Axios支持SSL Pinning

推荐使用react-native-ssl-pinning库来实现跨平台的SSL Pinning,替代Axios默认的网络适配器:

  1. 安装依赖:
npm install react-native-ssl-pinning --save
# 若使用RN 0.60+,自动link无需额外操作;低版本需要手动link
  1. 修改你的API调用代码,创建带SSL Pinning的Axios实例:
import axios from 'axios';
import { SSLPinning } from 'react-native-ssl-pinning';

// 配置SSL Pinning参数
const sslPinningConfig = {
  urls: ['https://my_domain:11443'],
  certificates: [
    {
      cert: require('./certificates/your_certificate.cer'), // 你的证书路径
      domain: 'my_domain',
      hash: 'sha256/你的证书SHA256哈希值', // 可选,用于更严格的验证
    },
  ],
  validateDomain: true,
};

// 创建自定义Axios实例
const secureAxios = axios.create({
  adapter: async (config) => {
    try {
      const response = await SSLPinning.sendRequest({
        ...config,
        sslPinning: sslPinningConfig,
      });
      // 适配Axios的响应格式
      return {
        data: response.data,
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        config: config,
      };
    } catch (error) {
      throw error;
    }
  },
});

// 用新实例发起请求
let dataToSend = {username: "rider1" ,password: "password"};
secureAxios.post('https://my_domain:11443/websrc/api/v1.0/auth/login', dataToSend)
  .then(function (response) {
    if (response.status === 200) {
      console.log(response.data);
    } else {
      console.log('Please check your email id or password');
    }
  })
  .catch(function (error) {
    console.log(error)
  });

第三步:分平台补充配置

Android 平台

  1. 将证书文件复制到android/app/src/main/res/raw目录(如果没有raw文件夹,手动新建)。
  2. 创建网络安全配置文件android/app/src/main/res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config>
    <domain includeSubdomains="true">my_domain</domain>
    <trust-anchors>
      <certificates src="@raw/your_certificate" /> <!-- 证书文件名,不带.cer后缀 -->
      <certificates src="system" /> <!-- 保留系统信任的证书 -->
    </trust-anchors>
  </domain-config>
</network-security-config>
  1. 在AndroidManifest.xml的application标签中添加配置引用:
<application
  ...
  android:networkSecurityConfig="@xml/network_security_config">

iOS 平台

  1. 将证书文件添加到Xcode项目:右键项目 -> Add Files to "YourProject",勾选Copy items if needed并选择对应的Target。
  2. 修改Info.plist添加ATS例外(仅测试环境使用,正式发布依赖SSL Pinning即可):
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>my_domain</key>
    <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.2</string>
    </dict>
  </dict>
</dict>
  1. M1 Mac模拟器额外操作:打开模拟器的Safari,访问https://my_domain:11443,当提示证书不可信时,点击「信任」,然后重启模拟器和App。

额外小技巧

  • 提取证书SHA256哈希值的命令:
openssl x509 -in your_certificate.cer -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64
  • 测试环境可以临时在原生层完全信任自签名证书,但正式发布必须用SSL Pinning,避免安全风险。

内容的提问来源于stack exchange,提问作者Ambili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:07:50