lishee loo
lishee loo

Reputation: 67

Android Network Security on API <24

To communicate with back from my android app I use network-security-config.xml, which looks like

<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="@raw/my_ca"/>
            <certificates src="system"/>
        </trust-anchors>
    </base-config>
</network-security-config>

where is my_ca - certificate (.pem file)

On API < 24 it's not working, how to solve this?

Upvotes: 2

Views: 2538

Answers (1)

Philippe Banwarth
Philippe Banwarth

Reputation: 17755

The declarative network security configuration was added in Android 7 (API 24). Before that you have to do it programatically. Unfortunately it is not straightforward, the steps are :

  • Put the certificate in a KeyStore
  • Create a X509TrustManager
  • Create a SSLSocketFactory
  • Build an OkHttpClient
  • Use the client in the Retrofit builder

There is OkHttp recipe describing this.

It seems that there also is an OkHttp extension with a much simpler API :

val certificate = """-----BEGIN CERTIFICATE-----
...                
-----END CERTIFICATE
""".decodeCertificatePem()

val certificates: HandshakeCertificates = HandshakeCertificates.Builder()
    .addTrustedCertificate(certificate)
    .addPlatformTrustedCertificates()
    .build()

val client = OkHttpClient.Builder()
    .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager)
    .build()

Retrofit.Builder()
    .client(client)
    ...
    .build()
    .create(MyWebService::class.java)

A similar sample in java building the OkHttp client

Upvotes: 4

Related Questions