React Native中使用自簽名證書https通信

http://facebook.github.io/react-native/docs/android-building-from-source.html

Android 設置

步驟1:

在新版本RN下,只需要在{project}/android 目錄下修改local.properties,添加一行

windows:(修改為自己路徑)

ndk.dir=C:\\Users\\your_name\\AppData\\Local\\Android\\android-ndk-r13b

mac: (修改為自己路徑)
ndk.dir=/Users/your_unix_name/android-ndk-r13b

步驟2:

android/build.gradle中添加gradle-download-task依賴

這里gradle-download-task的版本信息可以查看https://github.com/michel-kraemer/gradle-download-task/releases

dependencies {
    classpath 'com.android.tools.build:gradle:1.3.1'
    classpath 'de.undercouch:gradle-download-task:3.1.2'

    // 注意:不要把你的應用的依賴放在這里;
    // 它們應該放在各自模塊的build.gradle文件中
}

添加:ReactAndroid項目
在android/settings.gradle中添加:ReactAndroid項目

include ':ReactAndroid'

project(':ReactAndroid').projectDir = new File(rootProject.projectDir, '../node_modules/react-
native/ReactAndroid')

修改你的android/app/build.gradle文件,使用:ReactAndroid替換預編譯庫。例如用compile project(':ReactAndroid'):替換compile 'com.facebook.react:react-native:0.16.+'

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'

compile project(':ReactAndroid')

 ...
}
說明:

如果你使用第三方的React Native模塊,你需要重寫它們的依賴以避免它們仍然打包官方的預編譯庫。否則當你編譯時會報錯-Error: more than one library with package name 'com.facebook.react'.(錯誤:有幾個重名的'com.facebook.react'的包)

例:

修改你的android/app/build.gradle文件,替換compile project(':react-native-custom-module')為以下內容:

    compile(project(':react-native-custom-module')) {
       exclude group: 'com.facebook.react', module: 'react-native'
    }

步驟3:

在 \你的項目\node_modules\react-native\ReactAndroid\src\main\java\com\facebook\react\modules\network路徑下,

添加新java文件 HTTPSTrustManager.java

package com.facebook.react.modules.network;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
 * Created by eyow on 2016/5/25.
 *
 * @添加HTTPS信任
 */
public class HTTPSTrustManager implements X509TrustManager {
    private static final X509Certificate[] _AcceptedIssuers
            = new X509Certificate[] {};
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
            throws CertificateException {
        // To change body of implemented methods use File | Settings | File
        // Templates.
    }
    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
            throws CertificateException {
        // To change body of implemented methods use File | Settings | File
        // Templates.
    }
    @Override public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public static SSLSocketFactory allowAllSSLSocketFactory() {
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sc= SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
                @Override public X509Certificate[] getAcceptedIssuers() {
                    return _AcceptedIssuers;
                }
            } }, new SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslSocketFactory;
    }
    public static SSLSocketFactory buildSSLSocketFactory(InputStream inputStream) {
        KeyStore keyStore = null;
        try {
            keyStore = buildKeyStore(inputStream);
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = null;
        try {
            tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            sslContext.init(null, tmf.getTrustManagers(), null);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslContext.getSocketFactory();
    }
    private static KeyStore buildKeyStore(InputStream inputStream)
            throws KeyStoreException, CertificateException,
                   NoSuchAlgorithmException, IOException {
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        Certificate cert = readCert(inputStream);
        keyStore.setCertificateEntry("ca", cert);
        return keyStore;
    }
    private static Certificate readCert(InputStream inputStream) {
        Certificate ca = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ca = cf.generateCertificate(inputStream);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        return ca;
    }
}

修改OkHttpClientProvider.java文件

步驟1 :導入SSL相關包

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLSession;

步驟2:聲明SSLSocketFactory

private static SSLSocketFactory sslSocketFactory;

步驟3:在getOkHttpClient()方法中添加以下判斷

if (sslSocketFactory == null) {
      sslSocketFactory = HTTPSTrustManager.allowAllSSLSocketFactory();
 }

步驟4:在createClient()方法的Builder中添加

.hostnameVerifier(new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
    return true;
 }})
 .sslSocketFactory(sslSocketFactory)

ios https 通信

http://pengyl.cn/2016/0117/reactnative-fetch-selfsigned-https/

iOS端,通過查看fetch源碼,在追蹤到iOS代碼發(fā)現(xiàn)其實fetch最后都是走的Native,在Liabraries->RCTNetwork中,具體代碼

// RCTHTTPRequestHandler.m 文件遵循NSURLSessionDataDelegate協(xié)議,實現(xiàn)方法,從代碼上直接信任繞過驗證
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
if (RCT_DEBUG) {
   completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}}

說明

僅供參考 ,不同版本可能修改方式稍有不同

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容