A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding OAuth)
Join the DZone community and get the full member experience.
Join For Free(update : for trying out code posted on this blog post, kindly use the official/ locked emulator . the unlocked emulator images have a known issue with https )
as promised in the previous post(i know it was very long ago), we will
try to build a twitter application. building a twitter app is a very
easy task, and this post intends to guide you step by step in creating
your first twitter application. this post will speak about getting the
app authenticated/authorized using the oauth mechanism.
the target platform is windows phone 7 in this post, but you can pretty much a build a twitter app on any other platform based on this tutorial
step 1: register your twitter app on dev.twitter.com
twitter needs to know that you are writing an app which accesses/posts tweets on your behalf. you tell this to twitter by registering your app on twitter.
when registering your app, ensure that you set the application type to browser and specify a call-back url. (twitter has certain requirements on call-back urls, i.e. it will not accept non http urls ( you need to ask twitter specially for that ). for demo purposes, i have specified google.com as my default call-back url.you can specify your custom page hosted on your domain, if you want to
this is how your app settings on twitter would look like:
make a note of the highlighted urls and your consumer key and secret.( wondering what these are? continue reading or read about oauth here )
now comes the fun part, as usual fire up visual studio 2010. do a file | new project. select a
windows phone application
from
silverlight for windows phone
section.
twitter exposes a restful service to access a user’s tweets etc.
twitter as of now only allows oauth and xauth as the only authorization
mechanism. since we have to have to consume a rest service along with
oauth, we will be using a rest client helper, that abstracts a lot of
the hard work for me. (such as adding the necessary headers, computing
oauth parameters such as signature, nonce, timestamp etc. etc.)
for this demo, we’d be using the hammock rest client available for download
here
.
(ohh btw, hammock is a very good example as to how same source code can
target multiple platforms and multiple .net versions. curious , about
knowing how ? go straight to the site and download the source code and
have a look for yourselves.)
now lets get our hands dirty with some code for our first twitter application on windows phone 7

first using the consumer key and consumer key secret that you got
by registering your application on twitter’s site, you need to request
for a
request token
and
request token secret
request token and request token secret are temporary set of credentials that let you acquire oauth access tokens. the access token and access token secret are needed to access a user’s tweets.
to do this, i will use some neatly written helper classes in the hammock library.( else i would be actually writing code to do a lot of ugly stuff)
var oauth = new oauthworkflow { consumerkey = twittersettings.consumerkey, consumersecret = twittersettings.consumerkeysecret, signaturemethod = oauthsignaturemethod.hmacsha1, parameterhandling = oauthparameterhandling.httpauthorizationheader, requesttokenurl = twittersettings.requesttokenuri, version = twittersettings.oauthversion, callbackurl = twittersettings.callbackuri }; var info = oauth.buildrequesttokeninfo(webmethod.get); var objoauthwebquery = new oauthwebquery(info); objoauthwebquery.haselevatedpermissions = true; objoauthwebquery.silverlightuseragentheader = "hammock"; objoauthwebquery.silverlightmethodheader = "get";what this helper class does is, hide a lot of stuff from the end user that needs to be done to acquire the request token and secret. using the oauth webquery object all i have to do is to instantiate a hammock rest client object to fire a request to twitter’s servers.
var requesttokenquery = oauthhelper.getrequesttokenquery(); requesttokenquery.requestasync(twittersettings.requesttokenuri, null); requesttokenquery.queryresponse += new eventhandler(requesttokenquery_queryresponse);in the response received event, i parse the response sent across by twitter. this should have the request token and request token secret in the response body.
var parameters = helpermethods.getqueryparameters(e.response); oauthtokenkey = parameters["oauth_token"]; tokensecret = parameters["oauth_token_secret"]; var authorizeurl = twittersettings.authorizeuri+ "?oauth_token=" + oauthtokenkey;now using the request token and secret, we need to get our app authorized to read/write data from the end user’s twitter account. to do this, we need to open a web browser and redirect the end user to twitter’s sign-in/ authorize page. to do this, i will be using a web browser control and redirecting it to the authorize url i have created above.
dispatcher.begininvoke(() => { this.objauthorizebrowsercontrol.navigate(new uri(authorizeurl)); });
the user sees the twitter page, where s/he signs in to twitter. here, s/he is asked to authorize our twitter app.
after you have authorized the application to access your data on your behalf, twitter will send the
oauth request token
(you received in the previous step) and a
verification pin
. using these tokens, you can now request for the
access token
and
access token secret.
( arrgh!!! another set of tokens….)
using the hammock helper class that we used to get request tokens, we can acquire
access tokens
as follows:
var authorizeresult = helpermethods.getqueryparameters(e.uri.tostring()); var verifypin = authorizeresult["oauth_verifier"]; this.objauthorizebrowsercontrol.visibility = visibility.collapsed; //we now have the verification pin //using the request token and verification pin to request for access tokens var accesstokenquery = oauthhelper.getaccesstokenquery( oauthtokenkey, //the request token tokensecret, //the request token secret verifypin // verification pin ); accesstokenquery.queryresponse += new eventhandler(accesstokenquery_queryresponse); accesstokenquery.requestasync(twittersettings.accesstokenuri, null);
in response twitter sends us the access tokens, the userid and the
user’s screen name. i am going to store ‘em all, (can prove to be very
handy.)
var parameters = helpermethods.getqueryparameters(e.response); accesstoken = parameters["oauth_token"]; accesstokensecret = parameters["oauth_token_secret"]; userid = parameters["user_id"]; userscreenname = parameters["screen_name"]; helpermethods.setkeyvalue("accesstoken", accesstoken); helpermethods.setkeyvalue("accesstokensecret", accesstokensecret); dispatcher.begininvoke(() => { menuitemsignin.isenabled = false; menuitemsignout.isenabled = true; tweetbutton.isenabled = true; });phew!!! now we are authenticated. we can now use the tokens we have received till now and the app can now access the user’s data(such as tweets, timeline etc.)
twitter
Windows Phone
application
authentication
security
app
Requests
End user
Published at DZone with permission of Sudheendra Kovalam. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments