在控制台应用程序中,我想使用HttpClient
进行 http请求(GET)。我从REST服务团队那里获得了客户端证书,密钥和根CA (.pem
文件)。使用OpenSSL,我将这些证书(.pem
)覆盖到.pfx
文件中。我通过使用附加的 Postman 附加了.pfx
证书向其余服务发出Http GET来测试此证书。它像一种魅力。
问题是当我的控制台应用程序从文件系统加载客户端证书并执行Http GET时,它正在获得403-forbidden
响应。
当我在计算机上安装客户端证书并运行相同的代码时,客户端应用程序可以成功发送Http Get并接收Respose。
我的猜测是客户端应用正在尝试从证书存储中检索证书,并且未将证书附加到请求中。谁知道,为什么应用程序没有将证书附加到请求。
这是我的代码。
namespace TestClientApp
{
class Program
{
static async Task Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
var x509Certificate2 = new X509Certificate2(@"C:\TestClientAppDir\clientCert.pfx"),"<password>");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(x509Certificate2);
HttpClient client = new HttpClient(handler);
try
{
var response = await client.GetAsync("https://rest service url");
Console.WriteLine($"Server returned status: {response.IsSuccessStatusCode}, {response.StatusCode.ToString()} \n Content {await response.Content.ReadAsStringAsync()}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
client.Dispose();
}
Console.Read();
}
}
}