0

In Xamarin Forms app I am using System.Net.Http.HttpClient to establish connection to server via https. Visual Studio version 16.5.4, Xamarin Forms version 4.5.0.617, android: target framework: Android 9.0 (Pie), iOS: SDK version 13.4. I want to accept only one certificate that comes from CA. Just after start, before first request, I am validating server certificate by:

private const string SupportedPublicKey = "118SDD782...HA4JD";

        public static void SetUp()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertficate;
        }

        private static bool ValidateServerCertficate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var certKey = certificate?.GetPublicKeyString();
            return SupportedPublicKey == certificate?.GetPublicKeyString();
        }

Program is hitting breakpoint at SetUp method, but the breakpoint inside event is never hitted. I have put there Console.WriteLine() there methods to check if debugger is broken, but console is clear, so program never reach that code.

Right now application on both platforms, on emulators and real devices, behaves like it accepts all certificates, no matter where they come from and connect to other servers via https.

I have tried to change project properties on android: HttpClient implementation from "default" to "Managed" and "android" and on iOS: from "managed(default)" to "NSUrlSession (iOS 7+)" and "CFNetwork (iOS 6+)" to but there is no effect. How can I fix it?

1 Answer 1

1

Try to change your code to use the new HttpClientHandler.ServerCertificateCustomValidationCallback APIs from .NET Core.

public static void SetUp()
    {
        HttpClientHandler httpClientHandler = new HttpClientHandler();
        httpClientHandler.ServerCertificateCustomValidationCallback = ValidateServerCertficate;
    }

private static bool ValidateServerCertficate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        var certKey = certificate?.GetPublicKeyString();
        return SupportedPublicKey == certificate?.GetPublicKeyString();
    }

You could refer this on github

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer solved my problem. I have put this code in PCL project and it works on both platforms like a charm. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.