HostnameVerifier/okHttp does not recognize or honor custom Hostname header

188 Views Asked by At

I am working on an IoT (internet of things) application and need make API calls to a base station. According to the device documentation, when validating hostname the app needs to check that the common name on the server certificate matches the base station id. For this you set the request Hostname header as the id and then check that it matches with the common name in the certificate. I've been able to successfully set the Hostname as the id by either adding an Interceptor with a Host header eg. .addHeader("Host", "01234abcde567") or by adding the header through the Retrofit interface methods, eg. @Headers("Host: 01234abcde567")

However, when doing an API call, the HostnameVerifier's hostname callback always returns the IP address!!!

OkHttpClient.Builder()
.hostnameVerifier(HostnameVerifier { hostname: String, session: SSLSession ->

    ...

    Timber.e("$hostname") // prints "1.2.3.44" instead of manually set Host header

    if (matches(hostname, firstCn)) { // never matches
        return@HostnameVerifier true
    }
    return@HostnameVerifier false
})

I have an httpLoggingInterceptor which confirms the Hostname is successfully set as the id with both methods mentioned above:

// okhttp.OkHttpClient in Logcat, custom request headers

api-key: abc123
Host: 01234abcde567

yet the HostnameVerifier always returns the IP address as the Hostname

// okhttp.OkHttpClient in Logcat, API call fails

HTTP FAILED: javax.net.ssl.SSLPeerUnverifiedException: Hostname 1.2.3.44 not verified:
certificate: sha256/01234abcd1234abcd1234abcd1234abcd=
DN: CN=01234abcde567,O=Company Name,C=NL
subjectAltNames: []

Someone else had the same problem and the dev said okHttp should honor it. Setting the Host as the base station id works perfectly fine in Postman, why does HostnameVerifier/okHttp refuse to recognize the custom Host header? And how can I fix it?

0

There are 0 best solutions below