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

React Native中Axios是否支持证书固定?及实现方案咨询

Axios是否支持证书固定?

Axios本身没有内置的证书固定功能,它作为HTTP客户端仅专注于请求发送与响应处理的封装,这类安全校验逻辑需要依赖底层运行环境或额外的配置/扩展来实现。

React Native中实现API请求证书固定的正确方式

React Native的网络请求依赖原生平台的网络栈,因此最可靠的证书固定方案是在iOS和Android原生项目中分别配置,这种方式对Axios、Fetch等所有HTTP客户端都生效。以下是具体步骤:

1. 准备证书公钥哈希

首先获取目标API服务器证书的SHA-256公钥哈希,可通过openssl命令生成:

openssl s_client -connect your-api-domain:443 | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64

2. iOS平台配置

  • 打开React Native项目的iOS子项目(Xcode中打开ios/[项目名].xcworkspace)
  • 找到Info.plist文件,添加NSAppTransportSecurity字典,配置目标域名的证书固定规则:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>your-api-domain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSExceptionPublicKeys</key>
            <array>
                <string>生成的公钥哈希值</string>
            </array>
        </dict>
    </dict>
</dict>

3. Android平台配置

  • 将API服务器的证书文件(.cer格式)放入android/app/src/main/res/raw目录(若无raw目录则新建)
  • 在android/app/src/main/res/xml目录下创建network_security_config.xml文件(若无xml目录则新建),内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">your-api-domain.com</domain>
        <trust-anchors>
            <certificates src="@raw/your-certificate-file"/>
            <!-- 若使用公钥哈希,可替换为:<certificates src="sha256/公钥哈希值"/> -->
        </trust-anchors>
    </domain-config>
</network-security-config>
  • 修改AndroidManifest.xml的application标签,添加网络安全配置引用:
<application
    ...
    android:networkSecurityConfig="@xml/network_security_config">

4. JavaScript层辅助校验(可选)

若需要在JS层额外验证,可通过Axios响应拦截器结合原生模块暴露的证书信息实现,但这种方式仅作为补充,不能替代原生配置的安全性:

  • 编写原生模块获取服务器证书的公钥哈希并暴露给JS
  • 在Axios中添加响应拦截器,对比哈希值:
axios.interceptors.response.use(
  (response) => {
    // 通过原生模块获取当前请求的证书哈希
    const certHash = NativeModules.CertChecker.getCertHash();
    if (certHash !== '预存的公钥哈希') {
      throw new Error('证书校验失败');
    }
    return response;
  },
  (error) => Promise.reject(error)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:41:19