10
votes

I have a specific application that requires the use of client certificates for mutual authentication of HTTPS requests. The server has a flexible certificate validation policy that allows it to accept self-signed client certificates that are not present in the server's certificate store. This is known to work just fine using curl as a client.

What I've determined via testing and packet sniffing is that Microsoft's ASP.NET HttpClient tries to be overly smart during the SSL handshake. This particular client will only use a client certificate (from the WebRequestHandler.ClientCertificates collection) if it has chain of trust to one of the server's trusted roots. What I've observed is that if there are no certificates with chain of trust then the client simply won't send a certificate at all during the handshake.

This is understandable default behavior but is overly restrictive and there appears to be no way to turn it off. I have experimented with various other WebRequestHandler properties, including AuthenticationLevel and ClientCertificateOptions but to no avail.

Is there a way to force HttpClient to send a client certificate when it is available in the ClientCertificates collection, even though it appears that it will not validate on the server side? I'm open to both straightforward and dirty (reflection hacks) solutions as I really need this client to work.

2
Did you find any solution to this? - Daniel
Any ideas for this question? - Carsten Schütte
2018 and it's still the case :( - komsky

2 Answers

0
votes

I had the same issue and same no luck. Also observed a strange behaviour, when WebRequesthandler sometimes did send the certificate, depending on the thread / AppPool credentials.

I have managed to sort this out by replacing HttpClient with RestClient. RestClient is OpenSource and available via nuget.

RestSharp page

The API is very similar and does the required magic without moaning about the certificate:

        var restClient = new RestClient($"{serviceBaseUrl}{requestUrl}");
        X509Certificate certificate = GetCertificateFromSomewhere();
        restClient.ClientCertificates = new X509CertificateCollection { certificate };
        var request = new RestRequest(Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddParameter(new Parameter()
        {
            Type = ParameterType.RequestBody,
            Name = "Body",
            ContentType = "application/json",
            Value = "{your_json_body}"
        });

        IRestResponse<T> response = client.Execute<T>(request);
        if (response.ErrorException != null)
        {
            throw new Exception(response.Content, response.ErrorException);
        }
        return response.Data;
0
votes

I think you have multiple certs or need multiple certs and need to attach them. you can add as many certs to X509CertificateCollection. One of them must match the https server cert otherwise you cant call web service.

try
    {
        X509Certificate2 clientCert = GetClientCertificate("cert1");
         X509Certificate2 clientCert = GetClientCertificate("cert2");
        X509Certificate2 clientCert = GetClientCertificate("cert3");
        WebRequestHandler requestHandler = new WebRequestHandler();
        requestHandler.ClientCertificates.Add(clientCert1);
         requestHandler.ClientCertificates.Add(clientCert2);

requestHandler.ClientCertificates.Add(clientCert3); HttpClient client = new HttpClient(requestHandler) { BaseAddress = new Uri("http://localhost:3020/") };

        HttpResponseMessage response = client.GetAsync("customers").Result;
        response.EnsureSuccessStatusCode();
        string responseContent = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(responseContent);     
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception while executing the test code: {0}", ex.Message);
    }

then call this request.

private static X509Certificate2 GetClientCertificate( string probablerightcert)
{
    X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    try
    {
        userCaStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
        X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, probablerightcert, true);
        X509Certificate2 clientCertificate = null;
        if (findResult.Count == 1)
        {
            clientCertificate = findResult[0];
        }
        else
        {
            throw new Exception("Unable to locate the correct client certificate.");
        }
        return clientCertificate;
    }
    catch
    {
        throw;
    }
    finally
    {
        userCaStore.Close();
    }
}