Trusting all certificates with OkHttp

Ignoring developer certificate verification issues.

Sometimes we need to ignore the SSL certificate when working with a development or testing server. With OkHttp we can trust everyone certificates:

import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate

private fun OkHttpClient.Builder.trustAllSSL() {
    val trustAllCerts: Array<X509TrustManager> = arrayOf(
        object : X509TrustManager {
            @Throws(CertificateException::class)
            override fun checkClientTrusted(
                chain: Array<X509Certificate?>?,
                authType: String?
            ) {
                // nothing to do
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(
                chain: Array<X509Certificate?>?,
                authType: String?
            ) {
                // nothing to do
            }

            override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        }
    )
    val sslContext: SSLContext = SSLContext.getInstance("SSL")
    sslContext.init(null, trustAllCerts, SecureRandom())
    val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
    sslSocketFactory(sslSocketFactory, trustAllCerts[0])
    hostnameVerifier(HostnameVerifier { _, _ -> true })
}

Now we can use it like this:

OkHttpClient.Builder()
    .apply {
        if (isDebug) {
            trustAllSSL()
        }
    }
    .build()