DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding OAuth)

A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding OAuth)

Sudheendra Kovalam user avatar by
Sudheendra Kovalam
·
Jul. 12, 11 · News
Like (0)
Save
Tweet
Share
12.19K Views

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.

image

twitterappregistration

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:

appsettings

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 smile
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.
twiiter_homescreen twitter_startscreen twitter_signin twitter_signin_2 tiwtter_authorize
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.

Popular on DZone

  • Seamless Integration of Azure Functions With SQL Server: A Developer's Perspective
  • Beyond Coding: The 5 Must-Have Skills to Have If You Want to Become a Senior Programmer
  • Navigating Progressive Delivery: Feature Flag Debugging Common Challenges and Effective Resolution
  • When Should We Move to Microservices?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: