WebRequest not sending client certificate

后端 未结 1 1779
萌比男神i
萌比男神i 2021-01-05 03:17

I\'m writing a client for a REST API and to authenticate to the API I must use a cert that was provided to me.

this code is as follows:

public strin         


        
相关标签:
1条回答
  • 2021-01-05 03:50

    Your code loads the client certificate from a local file. You should have more success if you import the client certificate into the certificate store (which is highly recommended to protect the private key). Then your code should look more like this:

    public string GetCustomer(int custId)
    {
        // EDIT THIS TO MATCH YOUR CLIENT CERTIFICATE: the subject key identifier in hexadecimal.
        string subjectKeyIdentifier = "39b66c2a49b2059a15adf96e6b2a3cda9f4b0e3b";
    
        X509Store store = new X509Store("My", StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
    
        X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier, true);
        X509Certificate2 certificate = certificates[0];
    
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://api.foo.net/api/customer/v1/" + custId);
        req.ClientCertificates.Add(certificate);
    
        req.UserAgent = "LOL API Client";
        req.Accept = "application/json";
        req.Method = WebRequestMethods.Http.Get;
    
        string result = null;
        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }
        return result;
    }
    

    See Import a Certificate for instructions. The code assumes that you have imported the certificate with both public and private keys to the Personal certificates folder ("My") of the Current User.

    You do not need to supply a ServicePointManager.ServerCertificateValidationCallback. That allows your application to change how the server certificate is validated. That does not influence how the server validates your client certificate.

    0 讨论(0)
提交回复
热议问题