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

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.

clip_image001

clip_image002

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:

clip_image003

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

clip_image004

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)

view source

print?

01

var oauth = new OAuthWorkflow

02

{

03

     ConsumerKey = TwitterSettings.consumerKey,

04

     ConsumerSecret = TwitterSettings.consumerKeySecret,

05

     SignatureMethod = OAuthSignatureMethod.HmacSha1,

06

     ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,

07

     RequestTokenUrl = TwitterSettings.RequestTokenUri,

08

     Version = TwitterSettings.oAuthVersion,

09

     CallbackUrl = TwitterSettings.CallbackUri

10

};

11

12

var info = oauth.BuildRequestTokenInfo(WebMethod.Get);

13

var objOAuthWebQuery = new OAuthWebQuery(info);

14

objOAuthWebQuery.HasElevatedPermissions = true;

15

objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";

16

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.

view source

print?

1

var requestTokenQuery = oAuthHelper.GetRequestTokenQuery();

2

requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);

3

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.

view source

print?

1

Dispatcher.BeginInvoke(() =>

2

{

3

      this.objAuthorizeBrowserControl.Navigate(new Uri(authorizeUrl));

4

});

The XAML for the browser control would look something like this:

view source

print?

1

The User sees the twitter page, where s/he signs in to twitter. Here, s/he is asked to authorize our twitter app.

clip_image005

clip_image006

clip_image007

clip_image008

clip_image009

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:

view source

print?

01

var AuthorizeResult = HelperMethods.GetQueryParameters(e.Uri.ToString());

02

var VerifyPin = AuthorizeResult["oauth_verifier"];

03

this.objAuthorizeBrowserControl.Visibility = Visibility.Collapsed;

04

05

//We now have the Verification pin

06

//Using the request token and verification pin to request for Access tokens

07

08

var AccessTokenQuery = oAuthHelper.GetAccessTokenQuery(

09

                                             OAuthTokenKey,     //The request Token

10

                                             tokenSecret,       //The request Token Secret

11

                                             VerifyPin         // Verification Pin

12

                                          );

13

14

AccessTokenQuery.QueryResponse += new EventHandler(AccessTokenQuery_QueryResponse);

15

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.)

view source

print?

01

var parameters = HelperMethods.GetQueryParameters(e.Response);

02

accessToken = parameters["oauth_token"];

03

accessTokenSecret = parameters["oauth_token_secret"];

04

userID = parameters["user_id"];

05

userScreenName = parameters["screen_name"];

06

07

HelperMethods.SetKeyValue("AccessToken", accessToken);

08

HelperMethods.SetKeyValue("AccessTokenSecret", accessTokenSecret);

09

Dispatcher.BeginInvoke(() =>

10

{

11

    MenuItemSignIn.IsEnabled = false;

12

    MenuItemSignOut.IsEnabled = true;

13

    TweetButton.IsEnabled = true;

14

});

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.)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值