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

如何在React Native中使用Axios实现mutual TLS

在React Native中使用Axios实现双向TLS(Mutual TLS)

前置准备

  • 客户端证书:支持PKCS#12(.p12)或PEM格式的证书+私钥文件,若证书设置了密码需记录密码。
  • 服务端CA证书:PEM格式,用于验证服务端SSL证书合法性。
  • 证书文件放置:
    • iOS:拖入项目Resources文件夹,勾选"Copy items if needed"确保文件被打包。
    • Android:放入src/main/res/raw目录(目录不存在则手动创建)。

安装依赖

需要两个核心库:react-native-tls提供支持客户端证书的HTTPS Agent,react-native-fs用于读取本地证书文件:

npm install react-native-tls react-native-fs --save
# 或使用yarn
yarn add react-native-tls react-native-fs

实现步骤与代码示例

1. 读取证书文件

根据平台适配证书路径,读取并转换证书格式:

import RNFS from 'react-native-fs';
import { Platform } from 'react-native';

// 读取客户端证书(以.p12格式为例)
async function getClientCert() {
  let certPath;
  if (Platform.OS === 'ios') {
    certPath = RNFS.MainBundlePath + '/client.p12';
  } else {
    // Android读取raw目录证书可使用RNFS.readFileAssets('client.p12', 'base64')
    certPath = RNFS.DocumentDirectoryPath + '/client.p12';
  }
  const certBase64 = await RNFS.readFile(certPath, 'base64');
  return Buffer.from(certBase64, 'base64');
}

// 读取CA证书
async function getCACert() {
  let caContent;
  if (Platform.OS === 'ios') {
    const caPath = RNFS.MainBundlePath + '/ca.pem';
    caContent = await RNFS.readFile(caPath, 'ascii');
  } else {
    caContent = await RNFS.readFileAssets('ca.pem', 'ascii');
  }
  return caContent;
}

2. 创建带MTLS配置的Axios实例

通过react-native-tls的HttpsAgent注入客户端证书配置,生成专用Axios实例:

import axios from 'axios';
import { HttpsAgent } from 'react-native-tls';

async function createMtlsAxiosInstance() {
  const clientCertBuffer = await getClientCert();
  const caCert = await getCACert();

  const agent = new HttpsAgent({
    pfx: clientCertBuffer, // 若使用PEM格式证书+私钥,替换为cert(证书内容)和key(私钥内容)参数
    passphrase: 'your-cert-password', // 证书密码(如果有设置)
    ca: [caCert],
    rejectUnauthorized: true, // 生产环境必须开启,禁用会跳过服务端证书验证,引发安全风险
  });

  return axios.create({
    baseURL: 'https://your-mtls-enabled-server.com',
    httpsAgent: agent,
  });
}

// 使用实例发起MTLS请求
async function fetchMtlsData() {
  try {
    const mtlsAxios = await createMtlsAxiosInstance();
    const response = await mtlsAxios.get('/api/target-endpoint');
    console.log('请求成功:', response.data);
  } catch (error) {
    console.error('MTLS请求失败:', error.response?.data || error.message);
  }
}

关键注意事项

  • 证书格式适配:如果使用PEM格式的证书和私钥,需将pfx参数替换为cert(PEM证书字符串)和key(PEM私钥字符串)。
  • 平台路径差异:Android读取raw目录资源优先使用RNFS.readFileAssets,iOS直接读取主bundle路径即可。
  • 安全要求:生产环境必须保持rejectUnauthorized: true,否则会失去双向TLS的安全校验能力。
  • Android权限:若证书存放在外部存储,需在AndroidManifest.xml添加读取权限:
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:35:36