.NET - Authenticate with JAVA API (SSL/TLS Error) using Certificates

Viewed 388

So, for a few weeks I've been trying to make an .NET application to authenticate with an government Java API using an client certificate.

It was working fine for a couple of days and then I started to get this exception: "The Request was aborted: Could not create SSL/TLS channel.".

I know there is a lot of questions about this issue and I've tried all the solutions I could find, none has worked.

Here's the code:

        public async static Task<string> AuthenticateAsync()
    {
        var objT = default(string);
        HttpResponseMessage resultHttp;

        try
        {
            WebRequestHandler handler = new WebRequestHandler();
            var certificate = CertificateHelper.GetCertificateFromLocalMachine();
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CustomValidation);
            ServicePointManager.SecurityProtocol = /*SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls |*/ SecurityProtocolType.Ssl3;

            if (certificate != null)
            {
                //certificate.FriendlyName = "anAlias";
                X509Certificate2 cert = new X509Certificate2();
                cert.Import(@"D:\Documentos\DUE\Certificados\eCPF\usa esse\jhonatan.pfx", "*******", X509KeyStorageFlags.Exportable);

                handler.ClientCertificates.Add(cert);

                byte[] bytes = cert.Export(X509ContentType.Pkcs12);

                handler.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CustomValidation);
                using (var client = new HttpClient(handler))
                {
                    //! Uri base
                    client.BaseAddress = new Uri(Endpoint);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                                    new MediaTypeWithQualityHeaderValue("application/xml"));
                    client.DefaultRequestHeaders.Add("CurrentCultureName", "pt-BR");

                    client.DefaultRequestHeaders.Add("Role-Type", "DEPOSIT");
                    client.DefaultRequestHeaders.Add("User-Agent", "Chrome");
                    resultHttp = await client.PostAsync("/portal/api/autenticar", new ByteArrayContent(bytes));

                    if (resultHttp.StatusCode == HttpStatusCode.OK)
                    {
                        objT = await resultHttp.Content.ReadAsAsync<string>();
                    }
                    else
                    {
                        //! Tratamento de erro quando statuscode for diferente de 200 (Ok)
                        objT = await resultHttp.Content.ReadAsAsync<string>();
                    }
                }
            }
        }

Things I've tried:

  1. Use ServerCertificateValidationCallback to set a custom validation method (I've tried 3 different methods)
  2. Use SecurityProtocol to change protocols and test. If I set to an TLS protocol I get the HTTP error of "422 unprocessable entity".
  3. Test ServicePointManager.Expect100Continue set to true or false, it made no difference.
  4. Implement authentication using HttpResponseMessage, same error.
  5. Implement this solution, no success.
  6. Implement this solution, also with no success.
  7. Combinations of multiple solutions found online, no success.
  8. Pass client certificate in request as .pfx and .p12 files (using openssl to create different formats), same error.
  9. Parse DateTime as common formats to check if it wasn't an date issue, no success.

EDIT: There was instability with receiving the SSL/TLS error before I started getting this error everytime. For example, a few days back, I was receiving this error all day long, but at night, when I got home and tested it again, it was working fine. It worked fine for about a week, then it started to display the SSL/TLS error again.

0 Answers
Related