Twitter Login using HttpClient API in Windows Phone 8 & 8.1 Silverlight

1 1 1 1 1 1 1 1 1 1 Rating 0.00 (0 Votes)

We were recently working on updating the Geo Notification App for Windows Phone to add one more option for sending notification on arrival or departure of an address. The option was to ‘Send Tweet’.

The first and the foremost thing, was to login to Twitter. Unfortunately, Twitter does not have API like FacebookSDK. Our aim was to integration with Twitter using HttpClient API.
After researching on the internet, we first came across working sample in this post below MSDN website:

https://code.msdn.microsoft.com/windowsapps/Latest-Twitter-integration-a42e8bb6

However, the Hammock API had the old style calls (delegates / callback). With our Java background, we found the use of the latest async programming much easier for creating utility classes. So we pursued to find a way to use HttpClient. After researching further, we came across OAuth package at https://github.com/danielcrenna/oauth. This helped in creating the OAuth headers required for different authentication related calls.

Below are the three NuGet packages which needs to be installed before proceeding:
https://www.nuget.org/packages/OAuth/
https://www.nuget.org/packages/Microsoft.Net.Http

Before we review the Twitter authentication process, we need to login and create an app on Twitter developer website (http://apps.twitter.com). You will get the Consumer Key and Consumer Secret  which would be required during the authentication process from here. There will also be a call back URL which needs to be entered without which the process will fail. You can give any valid URL say http://www.google.com. But make sure, you do not miss the http part.

Process for login to Twitter

The steps are explained in detail at Implementing Sign in with Twitter implementing. However, we will go over and try to explain it from WP perspective. Note that all the requests are performed using the GET protocol.

1. Obtain a Request Token
This step involves making a GET call to /oauth/request_token. It requires OAuth headers which needs to be passed. This is where the OAuth Util comes into picture. It generates all the tough fields like oauth_signature. You will also need the keys which you collected from the Twitter development website. As part of the successful response, we get some tokens like oauth_token, oauth_token_secret which will be used in the subsequent step. Note that, this step happens even before the user sees the Twitter login screen.

2. Redirect the User to Login page of Twitter
In this step, we form an URL using /oauth/authenticate and appending the parameters which we received in step 1. Once we form the URL, we just use a browser control and redirect the user to the generated URL. This URL shows the user the login screen of Twitter. After the user successfully logs in and give the app permission to act on behalf of the user, it will redirect with the callback URL which you entered in the Twitter website along with few other parameters like oauth_token and oauth_verifier. You will use the oauth_verifier in the next step for getting access tokens.

3. Convert the request token to access token
We just call the URL /oauth/access_token with the parameters which we collected so far. Check the response for 200 status code and collect the parameters returned in oauth_token and oauth_token_secret. The oauth_token and oauth_token_secret is all we need to perform any calls like sending tweet. We save these tokens in a safe place for use as needed in the application.

Implementing the above process

First, whenever we click the ‘Sign in with Twitter’ button, we navigate the user to a different xaml page. This page will just house browser control and have code behind which would call the Twitter Utils which we created.
On the page load, we call the GetRequestToken and then redirect the user to Login page. The below code does that.

private async void GetRequestToken()
        {
           string strResponse = await TwitterUtil.RequestTokenAsync();
            if(!string.IsNullOrEmpty(strResponse)) {
                var parameters = StringUtil.GetQueryParameters(strResponse);
                OAuthTokenKey = parameters["oauth_token"];
                tokenSecret = parameters["oauth_token_secret"];
                var authorizeUrl = Constants.TWITTER_AUTHORIZATION_URI+ "?oauth_token=" + OAuthTokenKey;


                Dispatcher.BeginInvoke(() =>
                {
                    this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute));
                });
            } else {
                MessageBox.Show("We are currently unable to connect with Twitter. Kindly try again later.","Connection Error",MessageBoxButton.OK);
                if (this.NavigationService.CanGoBack)
                    this.NavigationService.GoBack();
            }
            
        }

Since we used the HttpClient API, we create await async methods instead of callbacks, which we love smile
Let us look at the TwitterUtil’s RequestTokenAsync method:

internal static async Task<string> RequestTokenAsync()
        {
            string strResponse = string.Empty;
            try
            {
                OAuthRequest client = OAuthUtil.GetOAuthRequestToken();
                IDictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", client.GetAuthorizationHeader());
                strResponse = await HttpClientWrapper.ExecuteGetAsync(Constants.TWITTER_REQUESTTOKEN_URI, headers);
                
            }
            catch (Exception e)
            {
                Debug.WriteLine("Unable to perform RequestToken from Twitter: " + e.StackTrace);
            }
            return strResponse;
        }

 The OAuthUtil uses the OAuth component which we downloaded as below:

internal static OAuthRequest GetOAuthRequestToken()
        {
            OAuthRequest client = new OAuthRequest
            {
                Method = "GET",
                Type = OAuthRequestType.RequestToken,
                SignatureMethod = OAuth.OAuthSignatureMethod.HmacSha1,
                ConsumerKey = Constants.TWITTER_CONSUMER_KEY,
                ConsumerSecret = Constants.TWITTER_CONSUMER_SECRET,
                RequestUrl = Constants.TWITTER_REQUESTTOKEN_URI,
                Version = Constants.TWITTER_OAUTH_VERSION,
                CallbackUrl = Constants.TWITTER_CALLBACK_URL,
                Realm = "twitter.com"
            };


            return client;
        } 

 The TwitterUtil invokes method on the HttpClientWrapper to execute GET request. We utilize this method for other calls like AccessToken etc.

internal static async Task<string> ExecuteGetAsync(string uri, IDictionary<string, string> headers) 
        {
            string strResponse = string.Empty;
            if (!string.IsNullOrEmpty(uri))
            {
                HttpClientHandler handler = new HttpClientHandler();
                handler.UseDefaultCredentials = true;
                HttpClient httpClient = new HttpClient(handler);

                if (headers != null)
                {
                    ICollection<string> keys = headers.Keys;
                    foreach (string key in keys)
                        httpClient.DefaultRequestHeaders.Add(key, headers[key]);
                    
                }

                HttpResponseMessage response = await httpClient.GetAsync(uri);
                strResponse = await response.Content.ReadAsStringAsync();
            }
            return strResponse;
        }

Similarly, the other calls for AccessToken are performed. We have attached partial code in the zip format which contains RequestTokenAsync(), AccessTokenAsync() and ValidateTokenAsync(). Note, that it might need to be adapted to your project as required and might not work right off the bat.
Below is the code in the zip file:
•    TwitterLoginPage.xaml
•    TwitterLoginPage.xaml.cs
•    Constants.cs
•    TwitterUtil.cs
•    HttpClientWrapper.cs

Download Partial Source Code

The TwitterUtil also has a method ValidateTokenAsync(), which validates the tokens (oauth_token and oauth_token_secret) which is received from the AccessTokenAsync(). You generally would call this to verify after retrieving the access tokens later, to see if they are still valid.

However, to conclude, we wanted to let know that, we were unable to perform POST calls using HttpClient and OAuth combination. We ended up using the TweetInvi API for sending tweets.


Joomla SEO by MijoSEF