Forcing ASP.NET WebAPI client to send a client certificate even when no CA match

前端 未结 2 1073
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 13:02

I have a specific application that requires the use of client certificates for mutual authentication of HTTPS requests. The server has a flexible certificate validation policy

2条回答
  •  失恋的感觉
    2021-02-08 13:45

    I think you have multiple certs or need multiple certs and need to attach them. you can add as many certs to X509CertificateCollection. One of them must match the https server cert otherwise you cant call web service.

    try
        {
            X509Certificate2 clientCert = GetClientCertificate("cert1");
             X509Certificate2 clientCert = GetClientCertificate("cert2");
            X509Certificate2 clientCert = GetClientCertificate("cert3");
            WebRequestHandler requestHandler = new WebRequestHandler();
            requestHandler.ClientCertificates.Add(clientCert1);
             requestHandler.ClientCertificates.Add(clientCert2);
    

    requestHandler.ClientCertificates.Add(clientCert3); HttpClient client = new HttpClient(requestHandler) { BaseAddress = new Uri("http://localhost:3020/") };

            HttpResponseMessage response = client.GetAsync("customers").Result;
            response.EnsureSuccessStatusCode();
            string responseContent = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(responseContent);     
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception while executing the test code: {0}", ex.Message);
        }
    

    then call this request.

    private static X509Certificate2 GetClientCertificate( string probablerightcert)
    {
        X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        try
        {
            userCaStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
            X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, probablerightcert, true);
            X509Certificate2 clientCertificate = null;
            if (findResult.Count == 1)
            {
                clientCertificate = findResult[0];
            }
            else
            {
                throw new Exception("Unable to locate the correct client certificate.");
            }
            return clientCertificate;
        }
        catch
        {
            throw;
        }
        finally
        {
            userCaStore.Close();
        }
    }
    

提交回复
热议问题