使用 C# Restsharp 库使用需要客户端证书和根证书的 Web 服务

Consuming webservice that requires Client Certificate and Root Certificate using C# Restsharp Library

我正在尝试使用要求开发人员将签名证书作为参数的一部分传递的 Web 服务。此服务在测试环境中运行良好,但是对于生产环境,除了签名证书外,还需要根证书才能成功访问该服务。这已经在 Postman 中进行了测试,因为它产生了成功的结果。

当使用 RestSharp 库在 C# 代码中实现时 我得到如下所示的响应。

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

我的问题是,如何使用 Restsharp 库在 C# 中实现它。下面是我实现这个的代码。但是我不断收到错误消息“请求被中止:无法创建 SSL/TLS 安全通道。


    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));

非常感谢您的建议。

错误与代码无关。出现此问题是因为我正在从浏览器访问该服务。然而浏览器并没有这个证书颁发机构的任何记录。必须将根证书添加到浏览器中的证书管理器中。以下是在 Firefox 浏览器中添加证书颁发机构的步骤。

工具->设置->隐私和安全->查看证书->权限->导入

First Screenshot on how to add certificate authority in Firefox Browser

Second Screenshot on how to add certificate authority in Firefox Browser

添加证书后,我就可以顺利访问该服务了。