android / codelab-android-network-security-config

Android Network Security Configuration codelab
https://codelabs.developers.google.com/codelabs/android-network-security-config
Apache License 2.0
78 stars 51 forks source link

Step 7 does not allow emulator to access local web server over SSL #8

Closed nickwjmz closed 3 years ago

nickwjmz commented 4 years ago

localhost directs to 127.0.0.1 but to access emulator's localhost you need to use the special address 10.0.2.2 according to this page in the docs.

To get the app to show the posts on the emulator I changed the following:

#Replace this line
openssl req -x509 -new -nodes -days 100 -key root-ca.privkey.pem -out root-ca.cert.pem -subj "/C=US/O=Debug certificate/CN=localhost" -extensions v3_ca -config openssl_config.txt

# With this one
openssl req -x509 -new -nodes -days 100 -key root-ca.privkey.pem -out root-ca.cert.pem -subj "/C=US/O=Debug certificate/CN=10.0.2.2" -extensions v3_ca -config openssl_config.txt

Change the line in the gradle.properties to this instead.

postsUrl="https://10.0.2.2:8080/posts.json"
  1. Finally, change the xml/network_security_config.xml file as follows: res/xml/network_security_config.xml

    
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    <base-config cleartextTrafficPermitted="false" />
    
    <domain-config>
        <domain includeSubdomains="true">10.0.2.2</domain>
        <trust-anchors>
            <!-- Trust a debug certificate in addition to the system certificates -->
            <certificates src="system" />
            <certificates src="@raw/debug_certificate" />
        </trust-anchors>
    </domain-config>



Everything else remained the same now it works on my emulated device. I'm sure there is another way to handle this, but this was the first solution I found.
nic0lette commented 3 years ago

I tried going through the codelab using an emulator (the emulator in Android Studio) and it worked with the steps in the codelab. Perhaps this was another emulator that works differently?

In either case, since it seems to be working in the default configuration, I'm going to close this.

If you have further details, including an idea for how it might be presented so it works both in your setup, in addition to the currents steps in the codelab, I'd be happy to accept a PR.