find a location for property in a new city

Wednesday, 11 January 2012

Adding a certificate to a request in .NET

Sometimes you need to send a security certficate with your WebRequest to authenticate with the web service you are accessing, e.g. a REST API via .NET. To authenticate you may need to send a certificate with your web request to authenticate with the API. This guide shows you how to do that using .NET.

First you need to be able to find your certificate. Sometimes it is hard to remember where exactly your certificate is so I have created two methods which together will search all usual locations until it finds the certificate based on its thumbprint.

This bit of code finds and returns the certificate:

//Returns a certificate by searching through all likely places
private static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
{
    X509Certificate2 certificate;
    //foreach likely certificate store name
    foreach (var name in new[] { StoreName.My, StoreName.Root })
    {
        //foreach store location
        foreach (var location in new[] {StoreLocation.CurrentUser, StoreLocation.LocalMachine})
        {
            //see if the certificate is in this store name and location
            certificate = FindThumbprintInStore(thumbprint, name, location);
            if (certificate != null)
            {
                //return the resulting certificate
                return certificate;
            }
        }
    }
    //certificate was not found
    throw new Exception(string.Format("The certificate with thumbprint {0} was not found",
                                       thumbprint));
}

private static X509Certificate2 FindThumbprintInStore(string thumbprint,
                                                      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.FindByThumbprint,
                                                     thumbprint, false);
    certStore.Close();

    if (certCollection.Count > 0)
    {
        //if it is found return
        return certCollection[0];
    }
    else
    {
        //if the certificate was not found return null
        return null;
    }
}

With this method created that gets a certificate you can now easily add a certificate to an HttpWebRequest like so:

var request = (HttpWebRequest)HttpWebRequest.Create("https://mysecureapi.com/listofsecrets");
var certificate = GetCertificateByThumbprint("23A43AE81F15CB000000000000000000000000000");
request.ClientCertificates.Add(certificate);
Now when you set up the rest of your request and GetResponse you will be sending the certificate also.

Follow britishdev on Twitter

6 comments: