I’m having issues getting my kotlin api 24 app to connect to my api endpoint. The issue is related to ssl trusting. I’ve already tried adding the certificate to jdk trust store, and adding it to res/raw and manipulating the xml file, but to no avail. I asked ai to write a custom trust manager. The issue is resolved but I can’t help but think this code will probably create security issues later on. Is this implementation ok? What can I do to improve it?
private const val BASE_URL = "https://***/api/"
// Custom trust manager that trusts the specific SSL certificate
private fun getUnsafeOkHttpClient(): OkHttpClient {
return try { // Create a trust manager that does not validate certificate chains
val trustAllCerts =
arrayOf<TrustManager>(object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(
chain: Array<java.security.cert.X509Certificate>,
authType: String,
) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(
chain: Array<java.security.cert.X509Certificate>,
authType: String,
) {
}
override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
return arrayOf()
}
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(
null, trustAllCerts, java.security.SecureRandom()
) // Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
OkHttpClient.Builder().sslSocketFactory(
sslSocketFactory, trustAllCerts[0] as X509TrustManager
)
.hostnameVerifier { hostname, session -> hostname == "textbookquiz.runflare.run" }
.build()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
private val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl(BASE_URL).client(getUnsafeOkHttpClient()).build()
interface QuestionApiService {
@GET("questions")
suspend fun getQuestions(): String
}
object QuestionApi {
val retrofitService: QuestionApiService by lazy {
retrofit.create(QuestionApiService::class.java)
}
}