Search code examples
android.netsslxamarin.formshttpclient

Xamarin Forms HttpClient SSL Certification validation error


I got pretty stuck with a problem in Xamarin.Forms (Forms though, but I only have an Android project, I need to support only that). The app must post to the backend, and the backend do SSL cert validation. I have a test device, an Android 11 Samsung. Among the user certificates on the device, there is the cert I need (Settings - Security - User certificates). When I open a Google Chrome on my phone, it loads the swagger UI of the backend, and I think it first asked me if I wanted to use my cert. The swagger works, I was able to try the endpoints there.

The problem is that I can't make a backend call from the app because it immediately drops my request with an SSL certification validation failed message. I wrote some quick test code with exact namespaces to understand what I'm doing:

// This returns the cert of the user's certificates:
Java.Security.Cert.X509Certificate myJavaCert = KeyChain.GetCertificateChain(this.ApplicationContext, "MyCertAlias").FirstOrDefault();

//Convert to X509Certificate2:
var myDotNetCert =  new System.Security.Cryptography.X509Certificates.X509Certificate2(myJavaCert.GetEncoded());

//I'm doing HttpClient manually, I don't want to use IHttpClientFactory yet:
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ClientCertificates.Add(myDotNetCert);
var httpClient = new HttpClient(httpClientHandler);

// Finally I call the post that runs for the above mentioned error:
await httpClient.PostAsync(url, objectToPost);

I’m pretty stuck with this task, I don’t really know where to try. Thanks for the help in advance too!


Solution

  • After one week of research I finally figured it out to myself. Here is the full-detailed answer for my own question: Xamarin Forms (Android) Client certificate from KeyStore vs PFX file