TheRiddler
TheRiddler

Reputation: 169

C# Rest call passing certificate

I have a RESTful endpoint that is protected by a certificate which is contained within my windows cert trust store and also in IIS. I am attempting to send that certificate to the RESTful endpoint to get authenticated and get a response.

So my endpoint is like : https://myrestful.ssl.endpoint/return/some/data

If I attempt to hit the endpoint direct from browser I get 401 no certificate chain in request which is what I would have expected trying to hit directly. However I am no trying to hit from my .NET code but I am still getting a 401 error. My current code is as below:

        var endpoint = "https://myrestful.ssl.endpoint/return/some/data";

        var client = new HttpClient(new HttpClientHandler
        {
             ClientCertificateOptions = ClientCertificateOption.Automatic 
        });

        var response = client.GetAsync(endpoint).Result;

Note the RESTful Endpoint I am hitting from my App hosted in IIS is hosted on Tomcat Server. I had read the below from this site :

The first option is to explicitly configure the HttpClient with a HttpClientHandler instance, containing its ClientCertificateOptions property set to Automatic. The resulting HttpClient can then be used normally: if during a connection handshake the server requires the client certificate, the HttpClientHandler instance will automatically select a compatible client certificate for the user’s personal certificate store.

However as I still am getting 401 response seems as though I am not sending the correct public cert which I need to the request. So if I have a cert in IIS with Common Name of my.first.cert - has anyone got the correct way I should be add this certificate to my client request in my code above?

Upvotes: 0

Views: 2002

Answers (1)

TheRiddler
TheRiddler

Reputation: 169

Was able to lift my certificate with the code below:

    private static X509Certificate2 FindSubjectNameInStore(string subjectName,
                                                          StoreName name, StoreLocation location)
    {
        //creates the store based on the input name and location e.g. name=My
        var certStore = new X509Store(name, location);
        certStore.Open(OpenFlags.ReadOnly);
        //finds the certificate in question in this store
        var certCollection = certStore.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
        certStore.Close();

        return certCollection.Count > 0 ? certCollection[0] : null;
    }

So I pass in the subject name of the cert I want. Still having an issue with connecting to my endpoint but I can post that in another question.

Upvotes: 1

Related Questions