httpClientHandler.ServerCertificateCustomValidationCallback never executed

1.9k Views Asked by At

I'm using Xamarin, in VS 2022, class libraries targeting .NetStanderd2.1, for Android.

I'd like to implement an HttpCient with custom SSL certificate validation.

Here's my code:

var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) =>
    {
        return true;
    };
var httpClient = new HttpClient(httpClientHandler);
httpClient.BaseAddress = new Uri(baseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(10);
HttpResponseMessage response =
    await httpClient.GetAsync("api/status");
response.EnsureSuccessStatusCode();

(somewhat prepared for legibility).

I switched the Xamarin HttpClient to Managed enter image description here

I understand the security implications of disabling SSL certificate validation, this is in a development environment, using a self-signed certificate.

If possible, I'd like to use TLS 1.2, but that problem is next.

The current problem is, that the custom SSL cert verification (return true;) in

httpClientHandler.ServerCertificateCustomValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) =>
    {
        return true;
    };

is never executed.

What am I doing wrong?

1

There are 1 best solutions below

0
On

This should be a known issue, you can check it here: https://github.com/xamarin/xamarin-android/issues/4688 .

But you can try to resolve it by changing the implementation of HTTP handler from xamarin to Android.

Please refer to the following code:

In form, create interface INativeHttpMessageHandlerProvider :

public interface INativeHttpMessageHandlerProvider
{
    HttpMessageHandler Get();
}

and create class HttpClientProvider

public class HttpClientProvider
{

        public HttpClient Get()
        {
            var nativeHttpMessageHandler = DependencyService.Get<INativeHttpMessageHandlerProvider>().Get();
            return new HttpClient(nativeHttpMessageHandler);   
            // nativeHttpMessageHander is injected from Android project
        }
    }

In android,implement interface INativeHttpMessageHandlerProvider

[assembly: Dependency(typeof(AndroidHttpMessageHandlerProvider))]
namespace SmartConnect.Droid.PlatformSpecific
{
    public class AndroidHttpMessageHandlerProvider : INativeHttpMessageHandlerProvider
    {
        public HttpMessageHandler Get()
        {
            return new AndroidClientHandler();
        }
    }
}

Refer : https://github.com/xamarin/xamarin-android/issues/4688#issuecomment-658833938