我需要创建一个c#应用程序,该应用程序必须使用SSL向服务器发送API请求.我需要创建客户端身份验证.我已经有服务器CA证书,客户端证书(cer),客户端私钥(pem)和密码.我找不到有关如何创建客户端连接的示例.有人可以建议我从小代码开始的地方很好解释吗?我手上有客户证书(PEM),客户提供密钥和客户密钥的密码.我不知道从哪里开始编写代码以向服务器发送请求
I need to create a c# application that has to send API request to a server using SSL. I need to create the Client authentication. I already have the server CA certificate, the client certificate (cer), the client private key (pem) and passphrase. I can't find an example on how to create the client connection. Can someone suggest me where to start with a small code well explained? In my hand I have the client certificate (PEM), the Client Provate Key and the Passphrase for the Client Key. I have no idea where to start to write the code to send a request to the server
推荐答案前一段时间,我创建了此POC 用于在.Net Core中使用证书进行客户端身份验证.它使用 idunno.Authentication 程序包现在 .Net Core中的内置.我的POC现在可能有点过时了,但这对您来说可能是一个很好的起点.
Some time ago I've created this POC for client authentication with certificate in .Net Core. It uses idunno.Authentication package that is now build-in in .Net Core. My POC probably is bit outdated now, but it can be a good starting point for you.
首先创建一个扩展方法,以将证书添加到 HttpClientHandler :
First create an extension method to add certificate to HttpClientHandler:
public static class HttpClientHandlerExtensions { public static HttpClientHandler AddClientCertificate(this HttpClientHandler handler, X509Certificate2 certificate) { handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ClientCertificates.Add(certificate); return handler; } }然后是将证书添加到 IHttpClientBuilder
public static IHttpClientBuilder AddClientCertificate(this IHttpClientBuilder httpClientBuilder, X509Certificate2 certificate) { httpClientBuilder.ConfigureHttpMessageHandlerBuilder(builder => { if (builder.PrimaryHandler is HttpClientHandler handler) { handler.AddClientCertificate(certificate); } else { throw new InvalidOperationException($"Only {typeof(HttpClientHandler).FullName} handler type is supported. Actual type: {builder.PrimaryHandler.GetType().FullName}"); } }); return httpClientBuilder; }然后加载证书并在 HttpClientFactory
var cert = CertificateFinder.FindBySubject("your-subject"); services .AddHttpClient("ClientWithCertificate", client => { client.BaseAddress = new Uri(ServerUrl); }) .AddClientCertificate(cert);现在,当您使用由工厂创建的客户端时,它将自动发送带有请求的证书;
Now when you will use client created by factory it will automatically send your certificate with the request;
public async Task SendRequest() { var client = _httpClientFactory.CreateClient("ClientWithCertificate"); .... }更多推荐
使用C#的证书进行SSL客户端身份验证
发布评论