将客户端证书添加到.net核心Httpclient [英] Add client certificate to .net core Httpclient

查看:113
本文介绍了将客户端证书添加到.net核心Httpclient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩.Net Core,并构建一个使用支付API的API。需要将客户端证书添加到双向SSL身份验证的请求中。
如何使用HttpClient在.Net Core中实现此目标?

I was playing around with .Net Core and building an API that utilizes payment APIs. There's a client certificate that needs to be added to the request for two-way SSL authentication. How can I achieve this in .Net Core using HttpClient?

我看过各种文章,发现HttpClientHandler不提供任何添加客户端的选项证书。

I have looked at various articles and found that HttpClientHandler doesn't provide any option to add client certificates.

请告知

推荐答案

我有一个类似的项目,我在服务之间以及移动和桌面服务之间进行通信。

I have a similar project where I communicate between services as well as between mobile and desktop with a service.

我们使用EXE中的Authenticode证书来确保执行请求的是我们的二进制文件。

We use the Authenticode certificate from the EXE to ensure that it's our binaries that's doing the requests.

在请求方(简化为该职位)。

On the requesting side (over simplified for the post).

Module m = Assembly.GetEntryAssembly().GetModules()[0];
using (var cert = m.GetSignerCertificate())
using (var cert2 = new X509Certificate2(cert))
{
   var _clientHandler = new HttpClientHandler();
   _clientHandler.ClientCertificates.Add(cert2);
   _clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
   var myModel = new Dictionary<string, string>
   {
       { "property1","value" },
       { "property2","value" },
   };
   using (var content = new FormUrlEncodedContent(myModel))
   using (var _client = new HttpClient(_clientHandler))
   using (HttpResponseMessage response = _client.PostAsync($"{url}/{controler}/{action}", content).Result)
   {
       response.EnsureSuccessStatusCode();
       string jsonString = response.Content.ReadAsStringAsync().Result;
       var myClass = JsonConvert.DeserializeObject<MyClass>(jsonString);
    }
}

然后我将以下代码用于请求

I then use the following code on the action that gets the request

X509Certificate2 clientCertInRequest = Request.HttpContext.Connection.ClientCertificate;
if (!clientCertInRequest.Verify() || !AllowedCerialNumbers(clientCertInRequest.SerialNumber))
{
    Response.StatusCode = 404;
    return null;
}

我们宁愿提供404而不是500,因为我们喜欢尝试url的用户以获得错误的请求,而不是让他们知道他们处在正确的轨道上

We rather provide a 404 than a 500 as we like those that are trying url's to get a bad request rather then let them know that they are "on the right track"

在核心中,获取证书的方法不再是通过遍历Module ,现代的方法可能对您有用:

In core, the way to get the certificate is no longer by going over Module, the modern way might work for you is:

private static X509Certificate2? Signer()
{
    using var cert = X509Certificate2.CreateFromSignedFile(Assembly.GetExecutingAssembly().Location);
    if (cert is null)
        return null;

    return new X509Certificate2(cert);
}

这篇关于将客户端证书添加到.net核心Httpclient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆