忽略Android React Native上的SSL证书检查

时间:2016-06-27 22:51:34

标签: javascript android ssl networking react-native

我目前正在使用Android上的原生作品。我正在使用 fetch()发出api请求,但请求给我一个网络请求失败,这是由于端点没有ssl证书。我能够通过修改一些xcode文件来删除iOS上的这项检查。 有没有办法忽略Android上的ssl证书检查?

3 个答案:

答案 0 :(得分:1)

/**
 * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
 * aid testing on a local box, not for use on production.
 */
private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

在此处找到:https://gist.github.com/aembleton/889392。不太确定它是否有效但它是一个开始!

答案 1 :(得分:1)

我也面临着同样的问题。我已经使用了rn-fetch-blob库。并将以下代码粘贴到index.js中。

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import RNFetchBlob from 'rn-fetch-blob';

AppRegistry.registerComponent(appName, () => App);
const Fetch = RNFetchBlob.polyfill.Fetch
// replace built-in fetch
window.fetch = new Fetch({
     // enable this option so that the response data conversion handled automatically
     auto : true,
    // when receiving response data, the module will match its Content-Type header
   // with strings in this array. If it contains any one of string in this array, 
  // the response body will be considered as binary data and the data will be stored
  // in file system instead of in memory.
  // By default, it only store response data to file system when Content-Type 
  // contains string `application/octet`.
  binaryContentTypes : [
    'image/',
    'video/',
    'audio/',
    'foo/',
 ],
 trusty : true
}).build()

如果仍然如此,则您在Android中遇到SSL握手问题,然后尝试使用以下解决方案。并从MainApplication.java中的onCreate()调用以下函数:-

 import android.annotation.SuppressLint;
 import java.security.SecureRandom;
 import java.security.cert.X509Certificate;

 import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSession;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;

 public class MainApplication extends Application implements ReactApplication {
    @Override
    public void onCreate() {
         super.onCreate();
         handleSSLHandshake();
         SoLoader.init(this, /* native exopackage */ false);
         initializeFlipper(this); // Remove this line if you don't want Flipper enabled
    }

    /**
    * Enables https connections
    */
   @SuppressLint("TrulyRandom")
    public static void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
               public X509Certificate[] getAcceptedIssuers() {
                  return new X509Certificate[0];
               }

              @Override
              public void checkClientTrusted(X509Certificate[] certs, String authType) {
              }

               @Override
               public void checkServerTrusted(X509Certificate[] certs, String authType) {
               }
           }};

           SSLContext sc = SSLContext.getInstance("SSL");
           sc.init(null, trustAllCerts, new SecureRandom());


     HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
          HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
               @Override
               public boolean verify(String arg0, SSLSession arg1) {
                  return true;
              }
           });
      } catch (Exception ignored) {
      }
    } 
 }

答案 2 :(得分:0)

注意:这是肮脏的解决方案

您可以修补Webview软件包

转到node_modules/android/src/main/java/com/reactnativecommunity/webview/RNCWebViewManager.java

onReceivedSslError 中将

更改handler.cancel() handler.proceed();像这样

@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
   // before: handler.cancel();
  handler.proceed();
}

如果您想进行补丁打包,则可以使用此patch-package