How to install a SSL certificate at the app level on Android

I found myself having issues after installing Charles Proxy Certificate at the OS level: the requests kept failing because of a SSL certificate issue.

After a few minutes, I couldn’t find the problem and to complete my task on time, Idecided to try another route : install and trust the certificate at the app level.

Steps :

1- Save Charles’ SSL root certificate

2- Add the certificate file to res/raw/ (note that files cannot be named with -)

2- Create a network_security_config.xml file in the res/xml/ directory of your project.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">your-domain.com</domain>
        <trust-anchors>
            <!-- Trust user certificates (if Charles Proxy cert is user-installed) -->
            <certificates src="user" />
        </trust-anchors>
    </domain-config>
    <base-config>
        <!-- Add a custom certificate bundled with the app -->
        <trust-anchors>
            <certificates src="@raw/charles_certificate" />
        </trust-anchors>
    </base-config>
</network-security-config>

4- Add the file to the App manifest

<application
        android:name=".ApplicationClass"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

5- Allow the certificate to be used on any domain

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">*</domain>
    </domain-config>
</network-security-config>