Friday, November 21, 2014

Catchpoint OAuth C#

I've been working recently on pulling web response performance data from Catchpoint. We need this to combine with website traffic as well as sales to see if the response time hinders conversion rate. This is my first time programming an OAuth2 authentication so I had a little trouble figuring out the necessary construct. Catchpoint Data Pull API and documentation is still under development so their is not much to go on. They give you one Curl example and the text of the request.

curl https://io.catchpoint.com/ui/api/token \
--data 'grant_type=client_credentials&client_id=<key>&client_secret=<secret>' 

POST /ui/api/token
Accept: application/json
Host: io.catchpoint.com
grant_type=client_credentials&client_id=<key>&client_secret=<secret>

So using the above information and some trial and error I was able to build a working C# use of their OAuth implementation to get the token I needed. I suppose if I was a linux programmer I would have know some of the defaults inherent in the curl command, but then, I wouldn't have been writing this in C# :)


                // Create the data to send
                StringBuilder data = new StringBuilder();
                data.Append("grant_type=" + Uri.EscapeDataString(grantType));
                data.Append("&client_id=" + Uri.EscapeDataString(clientString));
                data.Append("&client_secret=" + Uri.EscapeDataString(clientSecret));

                // Create a byte array of the data to be sent
                byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());

                // Setup the Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "application/json";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;

                // Write data
                Stream postStream = request.GetRequestStream();
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                // Send Request & Get Response
                response = (HttpWebResponse)request.GetResponse();

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    // Get the Response Stream
                    string json = reader.ReadLine();
                    Console.WriteLine(json);

                    // Retrieve and Return the Access Token
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    Dictionary<string, object> x = (Dictionary<string, object>)ser.DeserializeObject(json);
                    string accessToken = x["access_token"].ToString();
                    //Console.WriteLine(accessToken);
                }