前段时间我创建了this POC https://github.com/gao-artur/MtlsPoc用于使用 .Net Core 中的证书进行客户端身份验证。它用身份验证 https://github.com/blowdart/idunno.Authentication/tree/dev/src/idunno.Authentication.Certificate现在的包内置于.Net Core https://learn.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1。我的 POC 现在可能有点过时了,但它对您来说可能是一个很好的起点。
首先创建一个扩展方法来添加证书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;
}
然后加载证书并注册HttpClient
in HttpClientFactory
var cert = CertificateFinder.FindBySubject("your-subject");
services
.AddHttpClient("ClientWithCertificate", client => { client.BaseAddress = new Uri(ServerUrl); })
.AddClientCertificate(cert);
现在,当您使用工厂创建的客户端时,它会自动发送您的证书和请求;
public async Task SendRequest()
{
var client = _httpClientFactory.CreateClient("ClientWithCertificate");
....
}