Forcing ASP.NET WebAPI client to send a client certificate even when no CA match

前端 未结 2 1075
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 13:02

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

2条回答
  •  长发绾君心
    2021-02-08 13:53

    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 response = client.Execute(request);
            if (response.ErrorException != null)
            {
                throw new Exception(response.Content, response.ErrorException);
            }
            return response.Data;
    

提交回复
热议问题