C#、. Net Core私钥身份验证httpClient

Kac*_*ema 6 .net c# public-key-encryption private-key

我们的朋友在将私有证书加载到httpHandler时遇到问题。
我们正在使用.net核心,并且需要将所有应用程序托管在云中。
主要目标是从SQS获取消息并在使用消耗的数据之后执行一些指定的API快照。
我们的公钥/私钥证书有问题。我们尝试了所有可能的加载方式。

    public async Task<HttpResponseMessage> VisitHttps()
    {
        // Proceed for an invalid cerficate
        ServicePointManager.ServerCertificateValidationCallback +=
        (sender, certificate, chain, sslPolicyErrors) => true;

        // Add the certificate
        var handler = new HttpClientHandler();
        var cert = GetMyCert();
        if (cert != null)
        {
            handler.ClientCertificates.Add(cert);
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            //handler.PreAuthenticate = true;
        }
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;


        HttpClient cclient = new HttpClient(handler)
        {
            //BaseAddress = new Uri("https://someurl.com")

        };
        cclient.DefaultRequestHeaders.Accept.Clear();
        cclient.DefaultRequestHeaders.Accept.Add(new 

MediaTypeWithQualityHeaderValue("application/json"));
            return await cclient.GetAsync("https://some-url.com/ping"); }
Run Code Online (Sandbox Code Playgroud)

方法GetMyCert()如下所示:

string currentLocation = $"{AppDomain.CurrentDomain.BaseDirectory}key-public.crt";
                //var xcert = new X509Certificate2(currentLocation, "password");

                ////var currentLocationPriv = $"{AppDomain.CurrentDomain.BaseDirectory}key-private.crt";
                ////var privcert = new X509Certificate2(currentLocationPriv, "password", X509KeyStorageFlags.EphemeralKeySet);
                //var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                //certStore.Open(OpenFlags.ReadWrite);
                //certStore.Add(xcert);
                //certStore.Close();
            //return xcert;

            X509Store store = new X509Store("My", StoreLocation.CurrentUser);
            X509Certificate2 cert;
            cert = new X509Certificate2(File.ReadAllBytes(currentLocation), "password", X509KeyStorageFlags.MachineKeySet);
            bool result = cert.Verify();
            var r2 = result;
            return cert;
Run Code Online (Sandbox Code Playgroud)

带注释的行是我们尝试做的变化。
我们不知道我们还应该尝试解决什么问题。
任何指导方针都将受到欢迎

编辑:
我已经尝试在启动类中注册此,但似乎仍然无法正常工作。我总是在证书内的私钥字段为空。并将hasPrivateKey标记为false。

 private void CreateCert(IServiceCollection services)
    {
        string currentLocation = $"{AppDomain.CurrentDomain.BaseDirectory}key-public.crt";
        var certificate = new X509Certificate2(currentLocation, "password");
        services.AddHttpClient("TestClient", client =>
        {
            client.BaseAddress = new Uri("https://someurl.com");
        })
        .ConfigurePrimaryHttpMessageHandler(() =>
            {
            var handler = new HttpClientHandler();
            handler.ClientCertificates.Add(certificate);
            return handler;
        });
    }  
Run Code Online (Sandbox Code Playgroud)

我的测试代码:

        [Fact]
    public async Task ShouldPong()
    {
        var testClient = new TestClient()
        {
            BaseAddress = new Uri("https://someurl.com")
        };
        var result = await testClient.GetAsync("/ping");
        result.StatusCode.Should().Be(HttpStatusCode.OK);
    }
Run Code Online (Sandbox Code Playgroud)

TestClient:

public class TestClient : HttpClient
{
    public TestClient()
        :base()
    {

    }

    public TestClient(HttpMessageHandler handler)
        : base(handler)
    {

    }
}  
Run Code Online (Sandbox Code Playgroud)

编辑:
将.crt文件更改为.pfx文件时,该问题已解决。自从我们使用的API以来,其托管在nginx上。

Kac*_*ema 4

通过创建 .PFX 文件解决了该问题。我们访问的服务器托管在需要 .pfx 格式的 nginx 上。.crt 文件是 PEM 证书,对 nginx 无效。