Post #2: Use the .NET TweetSharp Library to Integrate with Twitter via OAuth

Today’s post is the second in a series explaining how to integrate TweetSharp into your .NET application using OAuth.  In our first post we covered the basics of registering a new application with Twitter.  This post will cover how you ask, then grant access from someone’s Twitter account to your new application using OAuth.

We will start by creating a very simple page in our application with a single button.  When clicked the button will begin the OAuth process via Twitter.  Essentially, the user will tell us they would like to grant acesss to their account from our application.  From there we will take their request, send the request to Twitter, then grab the response.

So our first step is to create a way for the user to let us know they would like to use our app.  As stated above, this will just be a simple button they user will click to start the process.

<code lang="csharp[lines]">

TweetSharp Demo

Clicking the button below will start the OAuth process, which will grant our application access to your Twitter account.

In our code behind we will start our process in the function tied to our button.  You will notice that I have set some variables that hold some of the values we set up in the first post.  When you registered your new application with Twitter they set us up a Consumer Key and a Consumer Secret.  We will use these as part of the request we pass back to Twitter.  So make sure you replace the variables below with the values from your application.  We have tied our click event to a function named Oauth_Click.  This function starts our OAuth process.  We first set up our request, then pass our user to Twitter.

<code lang="csharp[lines]">using System;<br></br>  
using Dimebrain.TweetSharp.Extensions;<br></br>  
using Dimebrain.TweetSharp.Fluent;<br></br>  
using Dimebrain.TweetSharp.Model;     ```

public partial class _Default : System.Web.UI.Page  
 {  
 private string _consumerKey = "YourKey";  
 private string _consumerSecret = "YourSecret";

 protected void Page_Load(object sender, EventArgs e)  
 {

 }

 protected void Oauth_Click(Object sender, EventArgs e)  
 {  
 var request = GetRequestToken();

 var authorizeUrl = FluentTwitter.CreateRequest()  
 .Authentication  
 .GetAuthorizationUrl(request.Token);

 Response.Redirect(authorizeUrl);  
 }

 private OAuthToken GetRequestToken()  
 {  
 var requestToken = FluentTwitter.CreateRequest()  
 .Authentication.GetRequestToken(_consumerKey, _consumerSecret);

 var response = requestToken.Request();  
 var result = response.AsToken();

 if (result == null)  
 {  
 var error = response.AsError();  
 if (error != null)  
 {  
 throw new Exception(error.ErrorMessage);  
 }  
 }

 return result;  
 }  
 }

So when our user clicks the button, they will see a message from Twitter asking if they would like to grant our app access.  From here the user can log into their Twitter account and verify our access to their account.

Easy so far!  Our last piece of completing the OAuth access is set up our callback URL.  Remember from our first post that we set up a callback URL as part of setting up our application.  This URL is where Twitter will send the response back to our application.  From here, we need to verify our response, then store the returned OAuth information for the user.

I set up my callback URL as welcome.aspx.  The display of this page is just a label, where we can pass the result to our user.

`<code lang="csharp[lines]">`


<title>Untitled Page</title>  

<form id="form1" runat="server"><div><label id="welcomeLabel" runat="server"></label></div></form>Once again in our code behind we will use the Consumer Key and Consumer Secret variables for our application.  When this page is loaded we will first check to make sure we have a valid request that has been returned from Twitter.  If not, you can trap this and do something like send the user back to our default page to try again.  If we do have a valid request returned, we can validate the credentials passed back to us and display a nice neat welcome message to our user.

using System;


using Dimebrain.TweetSharp.Extensions;


using Dimebrain.TweetSharp.Fluent;


using Dimebrain.TweetSharp.Model; ```

public partial class welcome : System.Web.UI.Page
{
private string _consumerKey = "YourKey";
private string _consumerSecret = "YourSecret";

protected void PageLoad(object sender, EventArgs e)
{
var requestToken = Request["oauth
token"];
if (requestToken == null)
{
//place your error code here, as no token was returned
}
else
{
// exchange returned request token for access token
var access = GetAccessToken(requestToken);

//verify returned info
var query = FluentTwitter.CreateRequest()
.AuthenticateWith(_consumerKey,
_consumerSecret,
access.Token,
access.TokenSecret)
.Account()
.VerifyCredentials()
.AsXml();

var response = query.Request();
var identity = response.AsUser();

//store the returned values for future use
//access.Token
//access.TokenSecret

//display welcome message
welcomeLabel.Text = "Welcome " + identity.ScreenName + ", you now have access to our demo application.";
}
}

private OAuthToken GetAccessToken(string requestToken)
{
var accessToken = FluentTwitter.CreateRequest()
.Authentication.GetAccessToken(_consumerKey, _consumerSecret, requestToken);

var response = accessToken.Request();
var result = response.AsToken();

return result;
}
}

We have now successfully set up access to our application for a user via OAuth.  One step that is not in this demo is storing the values returned from Twitter.  Depending on what you plan to do with your app, you will need to store these values for future API requests.  TweetSharp will return to you two variables, Token and TokenSecret for the user.  In my apps I store these in a database to grab for future use.

That’s it for today’s post.  Our final post in this series will show you how to post status updates via your application.

Comments

comments powered by Disqus