Home > front end >  Consuming webservice that requires Client Certificate and Root Certificate using C# Restsharp Librar
Consuming webservice that requires Client Certificate and Root Certificate using C# Restsharp Librar

Time:02-03

I am attempting to consume a Webservice that requires the developer to pass signed certificate as part of the parameters. This service works fine in the test environment, however for the production environment apart from the signed certificate, a Root Certificate is also required for you to access the service successfully. This has been tested in Postman as which yields successful results.

When this is implemented within the C# code using RestSharp library i get the response as indicated below.

Query Client Response Log: {"statusCode":0,"statusDescription":null,"content":"","headers":[],"responseUri":null,"errorMessage":"The request was aborted: Could not create SSL/TLS secure channel."}

My question is, how can i implement this in C# with Restsharp library. Below is a my code for achieving this. However i keep getting the error "The request was aborted: Could not create SSL/TLS secure channel."

    log.Info("-------------------Initiating Query Request---------------------------");
    
                QueryClient ad = new QueryClient();
                ad.institutionId = ConfigurationManager.AppSettings["OriginInst"];
                ad.proxyId = pr.proxyId;
                ad.requestSource = "XX";
                ad.requestTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string concat = ad.institutionId   ad.proxyId   ad.requestSource   ad.requestTimestamp;
                HelperLibrary hl = new HelperLibrary();
                string key = ConfigurationManager.AppSettings["pkey2"];
                string signature = hl.GetSignature(concat, key);
                ad.requestSignature = signature;
    
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.DefaultConnectionLimit = 9999;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                           | SecurityProtocolType.Tls11
                           | SecurityProtocolType.Tls12
                           | SecurityProtocolType.Ssl3;
    
    
                var client = new RestSharp.RestClient("https://service.url");
                
                //load certificates
                var myCert = new X509Certificate2(ConfigurationManager.AppSettings["certificatePath"], 
                    ConfigurationManager.AppSettings["certificatePassword"],
                    X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
                var rootCert = new X509Certificate2(ConfigurationManager.AppSettings["certificateRootPath"]);
    
                X509Chain chain = new X509Chain();
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.ExtraStore.Add(rootCert);
                X509CertificateCollection clientCerts = new X509CertificateCollection();
                clientCerts.Add(myCert);
                clientCerts.Add(rootCert);
               
                client.ClientCertificates = clientCerts;
                ServicePointManager.ServerCertificateValidationCallback  = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
                
                var request = new RestSharp.RestRequest(RestSharp.Method.POST);
                log.Info("Query Client Using Certificate Path: "   ConfigurationManager.AppSettings["certificatePath"]);
                request.AddHeader("accept", "application/json");
                request.AddHeader("content-type", "application/json");
                request.AddParameter("application/json", jsonString, RestSharp.ParameterType.RequestBody);
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var requestToLog = new
                {
                    resource = request.Resource,
                    parameters = serializer.Serialize(request.Parameters),
                method = request.Method.ToString(),
                    // This will generate the actual Uri used in the request
                    uri = client.BuildUri(request),
                };
                log.Info("Query Client Request: "   requestToLog);
    
                RestSharp.IRestResponse response = client.Execute(request);
                var responseToLog = new
                {
                    statusCode = response.StatusCode,
                    statusDescription = response.StatusDescription,
                    content = response.Content,
                    headers = response.Headers,
                    responseUri = response.ResponseUri,
                    errorMessage = response.ErrorMessage,
                };
                log.Info("Query Client Response Log: "   JsonConvert.SerializeObject(responseToLog));

Your suggestions will be much appreciated.

CodePudding user response:

The error had nothing to do with the code. The issue occurred because i was accessing the service from a browser. Yet the browser did not have any record of this certificate authority. The root certificate had to be added to the Certificate manager in the browser. Below are the steps for adding a certificate authority in a Firefox Browser.

Tools->Settings->Privacy & Security->View Certificates->Authorities->Import

First Screenshot on how to add certificate authority in Firefox Browser

Second Screenshot on how to add certificate authority in Firefox Browser

Once the certificate was added, i was able to access the service without hitches.

  •  Tags:  
  • Related