Restrict checkServerTrusted just for initialization of connection with my server

172 Views Asked by At

CheckServerTrusted is called when initialization with my server is made.

However checkServerTrusted is also called when Google maps are initialized.

Is it somehow possible to restrict checkServerTrusted just for initialization of connection to my server?

So I want to checkServerTrusted just to be called when initialization of connection with my server is made.

//CustomOkHttpClient

  public static OkHttpClient.Builder getCustomOkHttpClient() {
        try {

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            tmf.init((KeyStore)null);

            TrustManager[] trustManagers = tmf.getTrustManagers();
            final X509TrustManager origTrustmanager = (X509TrustManager)trustManagers[0];

            TrustManager[] wrappedTrustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return origTrustmanager.getAcceptedIssuers();
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                            origTrustmanager.checkClientTrusted(certs, authType);
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                            origTrustmanager.checkServerTrusted(certs, authType);
                            
                    }
            };

//ApiClient

 val builder = CustomOkHttpClient.getCustomOkHttpClient();
            client = builder.build()

            val retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()

            return retrofit.create(ApiInterface::class.java)
1

There are 1 best solutions below

0
Yuri Schimke On

You can allowlist specific servers with invalid certificates using

  val clientCertificates = HandshakeCertificates.Builder()
      .addPlatformTrustedCertificates()
      .addInsecureHost(server.hostName)
      .build()

  val client = OkHttpClient.Builder()
      .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)
      .build()

The code in https://github.com/square/okhttp/blob/f8fd4d08decf697013008b05ad7d2be10a648358/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt shows you how to implement on Android

For JDK https://github.com/square/okhttp/blob/f8fd4d08decf697013008b05ad7d2be10a648358/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt