Tuesday 11 June 2013

New Twitter API Version 1.1 (Part 1: Authentication)

As you know, the old twitter API V1 has been retired few hours ago [@twitterapi]. What does it mean for SharePoint developers? Well if you use any twitter webpart which using the API V1, then it is dead by now, because twitter depricate the API V1 and you need to upgrade your apps to use the new twitter API V1.1.
 Figure 1 - Twitter TimeLine Web part using API V1 (Before 11/06/2013)

Figure 2 - Twitter TimeLine Web part using API V1 (After 11/06/2013)

I have been trying to upgrade my company’s twitter web part to version 1.1, and find out there is very hard to find the relevant information from many resources out there. Finally after spending two days searching and trialing different solutions, I could do it, so here is the summary of what I found usefull, and a quick steps guide of what exactly needs to be done to build a reader webpart for twitter  timelines.
To use the Twitter API V 1.1, you must first authenticate (source), even if you only want to read timelines like in my case. After authenticate is done, you simply call the API and get the results in Json, and now you can display those data in whatever format you like to do it.
There aren't quick and easy instructions on how to move from that model because there aren't quick and easy ways to migrate. One has to completely rethink their approach to the API in this model, leveraging a server-to-server approach instead of a client-to-server model. Instead of using jQuery to make requests to the API, you'll need to make requests using OAuth from your back end. (Source from @episod)

Authentication (OAuth FAQ):

Before start coding, you need to create an application. https://dev.twitter.com/apps.
Once you've done that, you need to get your consumer key, consumer secret, access token and access token secret.




Here is a link to the twitter document for Moving from Basic Auth to OAuth. After many searching and reading, here is the best approach for my case to do the oAuth in SharePoint.
Thanks to @countscar and @bobbykc13 who post their codes here. this is what I did to build this code for SharePoint 2010.

To use/test this code, create a new web application in C# and copy this code to the Page Load function. Replace the "consumerKey, consumerSecret, accessToken, accessTokenSecret" with your own key details and run the application.

            // oauth application keys
            var consumerKey = "Your Key";
            var consumerSecret = "Your Key";
            var accessToken = "Your Key";//oauth_token
            var accessTokenSecret = "Your Key";//oauth_token_secret
            var Count = "3";

            // oauth implementation details
            var oauthSignatureMethod = "HMAC-SHA1";
            var oauthVersion = "1.0";
            // message api details
            //var status = "Updating status via REST API if this works";
            var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
            var screen_name = "TransPerth";

            // unique request details
            var oauth_nonce = Convert.ToBase64String(
               new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            var timeSpan = DateTime.UtcNow
                - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            // create oauth signature
            var baseFormat = "count={7}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
            var baseString = string.Format(baseFormat,
                                        consumerKey,
                                        oauth_nonce,
                                        oauthSignatureMethod,
                                        oauth_timestamp,
                                        accessToken,
                                        oauthVersion,
                                         Uri.EscapeDataString(screen_name),
                                         Uri.EscapeDataString(Count)
                                        );

            baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(consumerSecret),
                                    "&", Uri.EscapeDataString(accessTokenSecret));

            string oauth_signature;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            // create the request header
            var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                               "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                               "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                               "oauth_version=\"{6}\"";

            var authHeader = string.Format(headerFormat,
                                    Uri.EscapeDataString(oauth_nonce),
                                    Uri.EscapeDataString(oauthSignatureMethod),
                                    Uri.EscapeDataString(oauth_timestamp),
                                    Uri.EscapeDataString(consumerKey),
                                    Uri.EscapeDataString(accessToken),
                                    Uri.EscapeDataString(oauth_signature),
                                    Uri.EscapeDataString(oauthVersion)
                            );

            // make the request
            ServicePointManager.Expect100Continue = false;

            var postBody = string.Format("screen_name={0}&count={1}", Uri.EscapeDataString(screen_name), Uri.EscapeDataString(Count));
            resource_url += "?" + postBody;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
            request.Headers.Add("Authorization", authHeader);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            WebResponse response = request.GetResponse();
            string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //Label1.Text = responseData;
  
I will write another post soon, to explain the display method, and how convert the JSON results to a repeater and make the SharePoint web part.

No comments:

Post a Comment