Monday, 28 December 2015

Access WebApi using C# secured by certificate


Accessing the Webapi using the C# code and that WebApi is having SSL security.

Step 1: You have to install the SSL certificate into your local system and that you can check into MMC.

You should have the pfx file to install the certificate; you can follow the below steps to install certificates.

Step 2: You have to read the certificate by the thumbprint or by name, pass it to your code header like below; Code snippet to read the certificate as:
Need to import below namespace; using System.Security.Cryptography.X509Certificates;

/// <summary>
        /// Creating the certifactes
        /// </summary>
        /// <returns></returns>
        private static X509Certificate GetClientCert()
        {
            X509Store store = null;
            try
            {


                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

                /// Getting certificate by thumbprint
                var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "8e6cb255856e123457c3c395d12345758c0bf9b9", true); /// Generating the
                                                                                                                                      ///
               /// getting thye certificate by name  need to pass full name
                var certName = store.Certificates.Find(X509FindType.FindBySubjectName, "mycert.com", true); /// Generating the


                if (certs.Count == 1)
                {
                    var cert = certs[0];
                    return cert;
                }
            }
            finally
            {
                if (store != null)
                    store.Close();
            }

            return null;
        }

Step 3:  Asyn code to call the web api by passing the certificates and partner header,;
/// <summary>
        /// Calling the get sub to access the webapi
        /// </summary>
        /// <returns></returns>
        public static async Task<GetPIDetail> GetSub()
        {

            /// Please check with the WEB api url and the way of paramter passing it can be like https://getmscode/api/v1/Commerce/CustorDetail/1106671338454426
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://getmscode/api/v1/Commerce/CustorDetail?puid=1106671338454426"); // Pass the API URL

            request.ContentType = "application/json";

            request.ClientCertificates.Add(GetClientCert());
            request.Headers.Add("x-partnername", "SOME"); /// If there is any partner type that you need to pass from header
            try
            {
                List<GetPIDetail> objdeviceService = new List<GetPIDetail>();
              
                using (WebResponse webResponse = await request.GetResponseAsync())
                {
                    using (Stream webStream = webResponse.GetResponseStream())
                    {
                        StreamReader responseReader = new StreamReader(webStream);
                        string response =  await responseReader.ReadLineAsync();

                      
                        objdeviceService = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetPIDetail>>(response);
                    }
                }
                return objdeviceService.FirstOrDefault();
             
            }
            catch (WebException we)
            {
                string webExceptionMessage = we.Message;
            }
            return null;

        }

Step 4: Calling of above method to get the records.
  private static async Task Convert()
        {
            var value = await GetSub();
            string val = string.Empty;
            if(value != null)
            {
                 val = value.AccountId;
            }
            else
            {
                val = "it is null";
            }
            Console.WriteLine(val);
        }






No comments:

Post a Comment

Others

You will like to read it