Biscuit
Biscuit

Reputation: 5257

How to enable TLS 1.2 for whole application

I've been reading a lot about TLS1.2 that my application needs to support but each article is about either activating on Glide or on Retrofit is there a way to activate it once and for all for the application ?

My application is using:

I would like to avoid duplicating the same code on the OkHttpClient, for every library

Articles:

Upvotes: 0

Views: 2519

Answers (1)

Biscuit
Biscuit

Reputation: 5257

As suggested by @CommonsWare, to enable TLS 1.2 on the libraries I've created a single OkHttpClientBuilder that is then use by these libraries, here is the code:

I've created a gist with the same step as you'll find below.


Your clientBuilder

I've taken the custom socket from this gist and the related article

val clientBuilder by lazy {
    OkHttpClient.Builder()
        .readTimeout(15, TimeUnit.SECONDS)
        .connectTimeout(15, TimeUnit.SECONDS)
        .enableTls12()
}

Retrofit

Nothing too hard, just add client to the chain

val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addCallAdapterFactory(CoroutineCallAdapterFactory())
    .client(clientBuilder.build())
    .baseUrl(BASE_URL)
    .build()

Glide

We need to add these implementation to be able to custom Glide

implementation 'com.github.bumptech.glide:annotations:4.11.0'
implementation('com.github.bumptech.glide:okhttp3-integration:4.11.0'){
    exclude group: 'glide-parent'
}
@GlideModule
class CustomGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        registry.replace(
            GlideUrl::class.java,
            InputStream::class.java,
            OkHttpUrlLoader.Factory(clientBuilder.build())
        )
    }

}

Once this is in place, you just need to call:

GlideApp.with(this)
    .load(URL)
    .into(image)

Exoplayer

implementation "com.google.android.exoplayer:extension-okhttp:2.11.4"
val dataSourceFactory: DataSource.Factory = OkHttpDataSourceFactory(
    clientBuilder.build(),
    Util.getUserAgent(context, "RecyclerView VideoPlayer")
)

then just use your dataSourceFactory with your mediaSource and play the video

val videoSource: MediaSource = ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(Uri.parse(mediaUrl))

Upvotes: 1

Related Questions