Saturday, January 4, 2014

Calling a REST Web Service with an X509 certificate

I was recently looking at what client code I needed in order to call a REST web service that was secured with an X509 certificate.

In the first case I assume that the client device (maybe a tablet) has an X509 certificate installed.  So what code do I need to send some JSON to this REST web service and include the X509 certificate.  The simple example below works.  After that you will see the sample code for sending a user name and password with

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

namespace TestClientBizTalkService
{
    class Program
    {
        const string JsonPayload = "{\"ns0:Event\":{\"@xmlns:ns0\":\"
http://RESTDEMO.Event\",\"Id\":\"444\",\"Date\":\"1999-05-31\",\"Name\":\"A new event\"}}";
        static void Main(string[] args)
        {
            try
            {
                WebClientWithSslCertificate c = new WebClientWithSslCertificate();
               
                c.Headers[HttpRequestHeader.ContentType] = "application/json";
                string result = c.UploadString("
https://acesentinetpot/SelfHostedNode/BizTalkRestMutualX509", "POST", JsonPayload);
                Console.WriteLine("Service Returned: " + result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }

        class WebClientWithSslCertificate : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                request.ClientCertificates.Add(GetMyCertificate());
                return request;
            }

            private X509Certificate2 GetMyCertificate()
            {
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

                try
                {
                    store.Open(OpenFlags.OpenExistingOnly);
                    X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                    X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectName, "ClientTestCertificate", true);
                    if (fcollection.Count > 0)
                    {
                        return fcollection[0];
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    if (store != null)
                    {
                        store.Close();
                    }
                }
               
                return null;
            }
        }
       
    }
}

No comments: