Refresh certificate in mTLS connection with OkHttp

82 views Asked by At

I have some troubles to use mTLS in my Android application.

I setup a mTLS connection using this article https://developers.cloudflare.com/ssl/client-certificates/configure-your-mobile-app-or-iot-device/#embed-the-client-certificate-in-an-android-app

I'm using Koin to provide a OkHttp client to my repositories:

private val mTLSServiceModuke = module {
        factory<OkHttpClient> {
            val securityRepository: SecurityRepository = get()
            
            ApiFactory.provideMTLSOkHttpClient(
                tokenAuthenticator = getOrNull(),
                certificate = securityRepository.getCertificate()
                ....
            )
        }
    }

This certificate is from user and have a short expiration time (a few days). The problem is how to handle when this certificate expires.

When it happens, the backend (gateway) returns 401. Because I use authenticator (okhttp3.Authenticator) I'm able to handle this error and request another certificate without a mTLS connection. With a new certificate on hands, I would like to update my okhttp instance with the new certificate. This is tricky because new instances will use the new certificate but the current instance remains alive with the same sslSocketFactory. How can I provide a new certificate without create a new instance of okhttp instance?

0

There are 0 answers