3

I have an issue in my application Cleartext HTTP traffic to x not permitted.

I've already tried putting android:usesCleartextTraffic="true" in my manifest. But i want to change "android:usesCleartextTraffic" flag to "false" to prevent unencrypted traffic from being sent.

How to solve this?

SoftDev
  • 207
  • 3
  • 9

4 Answers4

13

You can fix this with one line of code. Open AssemblyInfo.cs in your android project under properties and add the code below:

[assembly: Application(UsesCleartextTraffic = true)]
Mordecai
  • 340
  • 4
  • 16
  • 3
    I might also recommend wrapping that in `#if DEBUG` and `#endif`, in case you want to only allow this behavior in debug builds. – Mike Nov 19 '21 at 10:02
3

If at some point you want to move to MAUI (which has no AssemblyInfo.cs), you might want to add UsesCleartextTraffic) to your Application attribute in Platforms/Android/MainApplication.cs:

#if DEBUG
[Application(UsesCleartextTraffic = true)]  // connect to local service
#else                                       // on the host for debugging,
[Application]                               // access via http://10.0.2.2
#endif
public class MainApplication : MauiApplication
{
    ...
}
thomiel
  • 1,968
  • 16
  • 33
2

In Maui, expand Platforms/Android and edit MainApplication.cs.

Replace "[Application]", near the top, with "[Application(UsesCleartextTraffic = true)]"

Mike
  • 21
  • 1
0

Assuming you are accessing a server that doesn't support HTTPS, then you can create exceptions in your network security config. You can create a file net_sec_conf.xml like this:

<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
  <base-config cleartextTrafficPermitted="false">
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
  </base-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">api.example.org</domain>
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
  </domain-config>
</network-security-config>

and then in manifest file add this line:

android:networkSecurityConfig="@xml/net_sec_conf"

(assuming you have put the file in xml folder). This way cleartext HTTP traffic will only be allowed for the specified domain.

Of course, if the server supports HTTPS, then you just need to change your URL "http://..." to "https://...".

adamm
  • 748
  • 1
  • 6
  • 15
  • I tried something like this, but could not found out how to make the net_sec_conf.xml to be added in the artifact. In side the apk file there was a res/xml folder, but it did not contain the added file net_sec_conf.xml. Solution from @Mordecai with the debug-comment from Mike worked for me. – Vering Feb 01 '22 at 13:13