我正在尝试使用使用证书作为身份验证方法的 API。
我尝试了两种方法,但遇到了同样的问题:
请求被中止:无法创建安全的 SSL/TLS 通道。
方法一:
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
string certificatePath = @"certificates/certificate.pfx";
string pass = "password";
handler.ClientCertificates.Add(new X509Certificate2(certificatePath, pass));
var client = new HttpClient(handler);
var dataToAuth = new StringContent(body, Encoding.UTF8, "application/json");
var request = client.PostAsync("https://api.com/oauth/v2/token", dataToAuth).GetAwaiter().GetResult();
var response = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return response;
方法二:
var client = new RestClient("https://api.com/oauth/v2/token");
client.Timeout = -1;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var certFile = Path.Combine(@"certificates/", "certificate.pfx");
X509Certificate2 certificate = new X509Certificate2(certFile, "password");
client.ClientCertificates = new X509CertificateCollection() { certificate };
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
string jsonPreInscription = new JavaScriptSerializer().Serialize(body);
request.AddParameter("application/json", jsonPreInscription, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
return response;
}
return response;
我真的看不出问题,我也尝试了使用 .cer 文件的两种方法,这是关键。
如有任何想法,我将不胜感激。
所以问题在于用于散列证书本身的方法。 当然,证书的版本需要
X509Certificate
方法,而不是我正在使用的 X509Certificate2
(对于我的情况)。
这是更新后的工作代码:
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
string certificatePath = @"certificates/certificate.pfx";
string pass = "password";
handler.ClientCertificates.Add(new X509Certificate(certificatePath, pass));
var client = new HttpClient(handler);
var dataToAuth = new StringContent(body, Encoding.UTF8, "application/json");
var request = client.PostAsync("https://api.com/oauth/v2/token", dataToAuth).GetAwaiter().GetResult();
var response = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
我希望没有人像我一样为解决这个问题而受苦:)