1

I need to send data to a webapi which needs a certificate to authorize. This is working on .net 4.5.2 with WebRequestHandler but when I try to upgrade to dotnet 5 and using HttpClientHandler I got an error:

Message: The SSL connection could not be established, see inner exception., InnerException Message: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.

.net 4.5.2 code

static async Task Main(string[] args)
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            var httpContent = new StringContent("json", System.Text.Encoding.UTF8, "application/json");

            var certificatepfx = new X509Certificate2(@"dpcert.pfx", "password");

            var handler = new WebRequestHandler();                
            handler.ClientCertificates.Add(certificatepfx);

            var httpClient = new HttpClient(handler);
            var response = await httpClient.PostAsync("someurl", httpContent);

            var returnValue = await response.Content.ReadAsStringAsync();
            Console.WriteLine(returnValue);

            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"error: {ex.Message} {ex.InnerException?.Message}");
        }
    }

.net 5 code:

static async Task Main(string[] args)
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };

            var httpContent = new StringContent("json", System.Text.Encoding.UTF8, "application/json");

            var certificatepfx = new X509Certificate2(@"dpcert.pfx", "password");

            var handler = new HttpClientHandler
            {
                SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
                ClientCertificateOptions = ClientCertificateOption.Manual
            };

            handler.ClientCertificates.Add(certificatepfx);

            using var httpClient = new HttpClient(handler);
            var response = await httpClient.PostAsync("someurl", httpContent);

            var returnValue = await response.Content.ReadAsStringAsync();
            Console.WriteLine(returnValue);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"error: {ex.Message} {ex.InnerException?.Message}");
        }
    }

What could be wrong in my code?

Shalom Dahan
  • 335
  • 7
  • 19

0 Answers0