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

19 comments:

  1. Awesome! Great work with this post, i am sure people should have got impressed with this post.

    ReplyDelete
  2. Excellent article. Very interesting to read. I really love to read such a nice article because it is very informative and useful for me. Thanks for nicely sharing.

    http://www.graphicdesigningcoursesinlahore.com/

    ReplyDelete
  3. Most employments today require something like a certificate and once you get that recognition, your choices are unending! In this way, venture outside of your usual range of familiarity and get your recognition. fake diploma

    ReplyDelete
  4. Wholesale printed custom perfume boxes with the highest quality and affordable prices. Free worldwide Delivery and free Custom Perfume Boxes design.

    ReplyDelete
  5. Buy online wholesale printed custom perfume boxes and packaging at easy prices and shipping worldwide, with 24/7 customer support. Get a free custom quote now!!

    ReplyDelete
  6. Blackbird packaging provide you with any size, shape design, custom cbd boxes sooner than any other packaging competitor in the market

    ReplyDelete
  7. cali spliff, available at Your Supplies. Cali Pack Heat sealable. Fast Shipping.

    ReplyDelete
  8. buy lawn collection online from afrozeh at best prices. get free shipping in pakistan

    ReplyDelete
  9. Shop from a wide range of Local and Imported variety of makeup removers and makeup remover wipes from Al-Fatah. Shop from a diversified range of makeup removers online from all top brands. Buy the best for your skin. Avail Free Delivery on orders above 1000 PKR for selected cities in Pakistan.

    ReplyDelete
  10. Blackbird packaging provide you with any size, shape design, custom bottle neckers wholesale wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  11. Thanks. I think you should change your website theme.
    This site is also hosted on blogger but with nice look.

    Wit Lifestyle

    ReplyDelete
  12. Buy sports inner wear for girls from dshred at easy prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  13. buy flex strappy sports bra online from dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  14. buy galaxy leggings online shopping online from dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  15. NDURE presents the ultimate fashion formula for men in the form of mens shorts. Get the best chino shorts from NDURE that are not only sports shorts but also great for everyday wear. Our wide range of shorts for men is crafted keeping in mind your comfort. So shop online to get your hands on the best shorts in Pakistan.wwww

    ReplyDelete
  16. buy tops for girls online online from Dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  17. buy Electronics online in Pakistan from Al-Fatah at best prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  18. Buy Online Summer lawn collection 2022 from Seran. Pakistani Top Designer embroidered Suits. Visit Our website now.


    ReplyDelete