Disclaimer: Bypassing SSL Certificate validation in production releases are not recommended. It can make your application vulnerable by hackers and reverse engineers, and your users will be unprotected from the bad guys. Consider to use the following codes with compile directives.
But in the other hand, it can be handful to just ignore the certification errors in development enviroment. Local machines has self signed certificates, and it is easier to just bypass the validation method, rather than set the self signed certificate acceptance in our client applications.
In Xamarin.Android (Lower than Android 10) and Xamarin.iOS, use the ServicePointManager in order to make your own certificate validator algorithm. The code below just accepts every cert.
ServicePointManager.ServerCertificateValidationCallback = (message, certificate, chain, sslPolicyErrors) => true;
To bring Android 10 also to work, construct your HttpClient with the following constructor:
var httpClientHandler = new HttpClientHandler(); #if DEBUG httpClientHandler.ServerCertificateCustomValidationCallback = (message, certificate, chain, sslPolicyErrors) => true; #endif var httpClient= new HttpClient(httpClientHandler);
2 thoughts on “Xamarin.Forms: Bypass SSL Certificate validation on Android”
Thank you for this article. I am struggling with an error, could you provide me some information?
I have Xamarin.Forms application what I test on an Android 11 Samsung device.
The Android keystore has a certificate as User trusted certificates. This certification is needed in order to post to the backend with https.
At the Android project I can get the Java.Security.Cert.X509Certificate with the KeyChain.GetCertificateChain() method. After that I convert this to the .NET version of X509Certificate2. When I call the PostAsync, I get the SSL certification validation error. On the device I can open the Swagger UI of the backend with Google Chrome (so I think the phone can use the certification).
Java.Security.Cert.X509Certificate myJavaCert = KeyChain
System.Security.Cryptography.X509Certificates.X509Certificate2 myDotNetCert =
var httpClientHandler = new HttpClientHandler();
var httpClient = new HttpClient(httpClientHandler);
httpClient.PostAsync(“…not important things…”);
We had a discussion about this problem in a Facebook group already.
For other readers, I do recommended to investigate the different behaviour of the implementations of the HttpClient class.