使用 c# 使用证书进行 SSL 客户端身份验证

Lor*_*nzo 5 c# authentication ssl client ssl-certificate

我需要创建 ac# 应用程序,该应用程序必须使用 SSL 将 API 请求发送到服务器。我需要创建客户端身份验证。我已经有了服务器 CA 证书、客户端证书 (cer)、客户端私钥 (pem) 和密码。我找不到有关如何创建客户端连接的示例。有人可以建议我从哪里开始解释一个很好的小代码吗?我手里有客户端证书 (PEM)、客户端证明密钥和客户端密钥的密码。我不知道从哪里开始编写向服务器发送请求的代码

Art*_*tur 5

前段时间,我创建了这个 POC,用于使用 .Net Core 中的证书进行客户端身份验证。它使用现在内置在 .Net Core 中的idunno.Authentication包。我的 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后另一种扩展方法将证书添加到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;
    }
Run Code Online (Sandbox Code Playgroud)

然后加载证书并HttpClient注册HttpClientFactory

        var cert = CertificateFinder.FindBySubject("your-subject");
        services
            .AddHttpClient("ClientWithCertificate", client => { client.BaseAddress = new Uri(ServerUrl); })
            .AddClientCertificate(cert);
Run Code Online (Sandbox Code Playgroud)

现在,当您使用工厂创建的客户端时,它会自动发送您的证书和请求;

public async Task SendRequest()
{
    var client = _httpClientFactory.CreateClient("ClientWithCertificate");
    ....
}
Run Code Online (Sandbox Code Playgroud)