Integrating Twitter Into An ASP.NET Website Using OAuthBy Scott Mitchell
Earlier this year I wrote an article about Twitterizer, an open-source .NET library that can be used to integrate your application with Twitter. Using Twitterizer you can allow your visitors to post tweets, view their timeline, and much more, all without leaving your website. The original article, Integrating Twitter Into An ASP.NET Website, showed how to post tweets and view a timeline to a particular Twitter account using Twitterizer 1.0. To post a tweet to a specific account, Twitterizer 1.0 uses basic authentication. Basic authentication is a very simple authentication scheme. For an application to post a tweet to JohnDoe's Twitter account, it would submit JohnDoe's username and password (along with the tweet text) to Twitter's servers. Basic authentication, while easy to implement, is not an ideal authentication scheme as it requires that the integrating application know the username(s) and password(s) of the accounts that it is connected to. Consequently, a user must share her password in order to connect her Twitter account with the application. Such password sharing is not only insecure, but it can also cause difficulties down the line if the user changes her password or decides that she no longer wants to connect her account to certain applications (but wants to remain connected to others).
To remedy these issues, Twitter introduced support for OAuth, which is a simple, secure protocol for granting API access. In a nutshell, OAuth allows a user to connect an application to their Twitter account without having to share their password. Instead, the user is sent to Twitter's website where they confirm whether they want to connect to the application. Upon confirmation, Twitter generates an token that is then sent back to the application. The application then submits this token when integrating with the user's account. The token serves as proof that the user has allowed this application access to their account. (Twitter users can view what application's they're connected to and may revoke these tokens on an application-by-application basis.)
In late 2009, Twitter announced that it was ending its support for basic authentication in June 2010. As a result, the code examined in Integrating Twitter Into An ASP.NET Website, which uses basic authentication, will no longer work once the cut off date is reached. The good news is that the Twitterizer version 2.0 supports OAuth. This article examines how to use Twitterizer 2.0 and OAuth from a website. Specifically, we'll see how to retrieve and display a user's latest tweets and how to post a tweet from an ASP.NET page. Read on to learn more!
An Overview of the Demo
Before we look at using Twitterizer to integrate an ASP.NET website with Twitter, let's first take a moment to review the demo application (which is available for download at the end of this article). The demo is quite similar to the demo presented in Integrating Twitter Into An ASP.NET Website - it consists of an ASP.NET page,
Default.aspx, along with a master page,
Site.master. The master page and CSS rules define a layout that divides the screen into left and right portions. The right portion contains page-specific content. The left portion shows the most recent tweets of the user visiting the site and appears on every page that uses the master page.
When a user visits the demo website for the first time, the
Default.aspx page shows a "Sign in with Twitter" button at the bottom of the page. Clicking this
button takes the user to the Twitter website where they are asked whether they want to connect with the application. After allowing access, the user is redirected back
to the demo application with a token granting access to their account (which also includes their Twitter UserID). This token is then cached in session and is used to know
the Twitter account of the visiting user and serves as authorization for having the demo website post tweets to that account.
If this doesn't make sense just yet, don't worry. We'll explore how OAuth works and how it is handled in the website and through Twitterizer in a moment. For now, you only need to understand that when the user comes to the website the website does not know the visitor's Twitter account, but by clicking the Sign in with Twitter button, the user is sharing that information with the website and granting it access to post tweets to his account.
The screen show below shows the demo application after having signed in with the Twitter user aspIntegration. (The left portion of the page lists the user's timeline. This left portion is defined in the master page so it will appear on all pages across the website.) There are four full tweets shown in the screen shot below, the most recent one listed at the top - "I am using OAuth. I AM USING OAUTH!!" What's more, the master page uses the ASP.NET Ajax Library's UpdatePanel and Timer Web controls to automatically and seamlessly refresh the list of latest tweets every 60 seconds.
Default.aspx page (shown above) includes a text box where the user can enter text that will be tweeted to his Twitter account. Clicking the "Post My Tweet"
button causes a postback, and on postback the page uses Twitterizer to make this tweet and to refresh the list of latest tweets is refreshed to include the just-tweeted post.
|Before You Run The Demo...|
|There are some steps you'll need to perform before you can run the demo. These steps are covered in detail in the "Getting the Demo to Run" section later in this article.|
Getting Started With Twitterizer
Using Twitterizer in one of your projects is easy - just download the Twitterizer assembly, copy it to your application's
/Binfolder, and start coding! The download available at the end of this article includes the latest version of Twitterizer at the time of writing, version 188.8.131.52. To get the latest version of Twitterizer, visit Twitterizer.Net and go to the Downloads page.
The Twitterizer library contains a number of classes that model the information exchanged between the client and the server when making Twitter API calls, along with the
low-level plumbing necessary to make the HTTP requests and to serialize the object model into the appropriate XML and vice-a-versa. For example, to get information about a
user use the
TwitterUser class. The following code shows how to retrieve a particular user's timeline (e.g., their most recent tweets):
Displaying Recent Tweets
Site.mastermaster page defines the markup and code used to display the visiting user's most recent tweets. The latest tweets are displayed using a ListView control, although the markup could certainly be rendered iteratively, by using a Repeater, or through some other mechanism. The master page's source code portion contains a public method named
RefreshTweetsthat, when called, uses the Twitterizer library to go and get the user's most recent tweets; this collection of tweets is then bound to the ListView control.
The markup to display the latest tweets follows. The data-binding syntax is highlighted in red. Keep in mind that the ListView is being
bound to a list of
TwitterStatus objects. The
TwitterStatus class has properties like
CreatedDate, which return the
text of the tweet and the date and time is was posted, respectively. There's also a
TwitterUser property, which returns a
TwitterUser object with information about the
user who posted the tweet. To reference these properties, use the data-binding syntax
<%# Eval("propertyName") %>.
Check out the formatting function
RelativeTime takes in an absolute time -
(the date and time the tweet was made), compares it to the current time, and generates a relative time value. For example, if a tweet was made on May 11th, 4:50 PM GMT
and the current universal time is May 11th, 5:01 PM GMT, the
RelativeTime method will return the string, "about 6 minutes ago."
The ListView of tweets is contained inside of an UpdatePanel control, which also contains a Timer. The Timer is configured to "tick" every 60 seconds. Whenever the Timer control
"ticks" it causes a postback; because the Timer is in an UpdatePanel it's a partial page postback. On postback, the Timer's
Tick event fires and the event handler
runs. This event handler calls the
RefreshTweets method, which uses Twitterizer to reload the most recent tweets in the ListView. Long story short, this setup will
seamlessly requery Twitter every 60 seconds. Any new tweets will automatically appear in the ListView. For more information on using the Timer control to seamlessly update
web page content, check out Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Using the Timer Control.
Tweeting From The Website
Twitterizer makes it easy to post a tweet on behalf of a Twitter user, which means you can offer users a text box on your website from which they can post tweets. Or you could automatically post a tweet on behalf of your users. For instance, an online game website might allow its users to have their high scores automatically tweeted to their Twitter accounts. The demo's
Default.aspxpage includes a text box and button. When the button is clicked, a postback ensues and the contents entered into the text box are posted to the visiting user's Twitter account.
Before you can send tweets on behalf of a user, the user must grant your application access to their account. We'll explore the inner workings of this process momentarily, but for now understand that when a user grants you access to their account they do so by sending you a token. This token serves as proof that the user has authorized your application access to their Twitter account. Whenever you want to read non-public data or make a tweet you need to send along this token to Twitter as proof that you can perform the requested operation. Keep in mind that this token can be cached, as it does not expire and therefore remains valid forever (unless the user revokes it). The demo application caches the token in session, but there's no reason it couldn't be stored in a database.
In order to connect your application to users' Twitter accounts, you must first register your application with Twitter at http://twitter.com/apps/new. The registration form asks for various bits of information - the application name, a description, the organization name, and so forth - fill these in as you see fit. The final four questions in the form are the most important ones:
- Application Type - This question asks where your application runs from - a desktop client or a web browser - as the authorization process differs on whether the application connecting to Twitter is being run from the desktop or the web. This article assumes that you will be integrating with Twitter from a website. Therefore, choose the "Browser" option.
- Callback URL - When a user authorizes your application to access their Twitter account they do so from Twitter's website. After granting access, Twitter will
send the user back to your website with information needed to go and get the token. This information is sent to the URL you specify here, which should be a URL on your
- Default Access Type - choose whether your application requires read-only or read and write access to users' Twitter accounts. If you plan on having your application post tweets you will need to choose the "Read & Write" option.
- Use Twitter for Login - Choose, "Yes, use Twitter for login."
Once the application has been registered, we are ready to setup the authorization workflow, which will allow visitors to our site the ability to connect our application to their Twitter account. This authorization process involves three steps. Let's walk through them one at a time.
Step 1: Sending the User to Twitter's Site for Authorization
To start the authorization workflow we need to send the user to Twitter's website where they will confirm whether they want to grant our application access to their account. Specifically, we need to send the user to the URL
https://twitter.com/oauth/authorize?oauth_token=consumer_token. The consumer_token passed along in the querystring identifies the application that is requesting access to the user's account. Twitterizer can generate this token value given our consumer key and consumer secret.
When a user visits the demo application for the first time, a "Sign in with Twitter" image is displayed (see the screen shot below). This is actually an ImageButton. When it
is clicked, a postback ensues and the ImageButton's
Click event handler constructs the consumer_token and then redirects the user to
The highlighted line in the code snippet below calls the Twitterizer library's
which creates the consumer_token that needs to be sent to Twitter's website.
Step 2: The User Authorizes the Application To Access Their Account
When the user clicks the "Sign in with Twitter" image there is a postback and they are redirected to the Twitter website. Here they are asked whether they want to allow or deny the application's request to connect to their account.
Step 3: Returning to the Application Site and Retrieving the Access Token
If the user allows the application access to their account then Twitter redirects the user to the application's Callback URL passing along a token in a querystring parameter named
oauth_token. This querystring token isn't the token that actually grants access to the user's account; rather, it is a token that simply says, "You can come and get the access token now." To go and get the access token, the Callback URL page needs to go back to Twitter, passing along the token sent in the querystring along with the application's consumer key and consumer secret. Fortunately, the Twitterizer library handles this for us - we just need to call the
GetAccessTokenmethod of the
OAuthUtilityclass, passing in the necessary information.
The following code is executed from the
Page_Load event handler of the
Callback.aspx page in the demo. Keep in mind that the
requestToken variable holds the value sent to the Callback URL via the
oauth_token querystring parameter. This value, along with the consumer key and
consumer secret, are then sent to Twitter to retrieve the access token. Whenever the application needs to perform a privileged action on the user's account (such as posting a
tweet) it must send along the access token information and its consumer key and consumer secret. This information is packaged up in an
OAuthTokens object, which
has properties to store the necessary bits of information. The code below creates such an object, populates its properties, and then caches it in a session variable.
Whew! The authorization process requires a bit of work, but once you have that token it is good forever, or until the user explicitly revokes it. Therefore, it's probably ideal to store the access token information (namely the access token and access token secret) in a database. For example, if you are storing user account information in a database you could add a new table that recorded the access token and access token secret for each user who has granted you access to the Twitter account.
Once all of the authorization work has been done, we can post a tweet. The code is pretty straightforward - call the
Update method, sending along the access token (which we have cached in the session variable
AccessToken) and the text to tweet.
That's all there is to it!
Getting the Demo to Run
Most of the demos available for download here on 4Guys are very easy to run - you just unzip the files to a folder on your computer, fire up Visual Studio and use the File -> Open Website option to open the folder where the files were unzipped, and hit F5 to launch the application. Couldn't be easier.
Unfortunately, this demo requires a little more work to get running. In short, you can't use the ASP.NET Development Web Server to host the application; instead, you've got to
use IIS, at least if you want to run the demo application using the ASP.NET Integration w/OAuth application that I created. (This is the application whose consumer key
and consumer secret are in the
When setting up the ASP.NET Integration w/OAuth application, I set its Callback URL setting to
http://127.0.0.1/Twitter2/Callback.aspx. This means that
after a visitor is sent to Twitter to authorizes the application to access her account, she will be redirected to
IP address - 127.0.0.1 - is the
localhost IP address, meaning that the user will be redirected to their own computer. Of course, in a real-world setting you
would have the Callback URL point to a URL on your website, something like
http://www.yoursite.com/TwitterCallback.aspx. For this demo, though, I wanted the
request to come back to my server (or yours, when you're testing it), which is why I used 127.0.0.1. For the
demo to work it is imperative that the demo site on your computer can be visited via
To accomplish this, start by downloading the demo site and unzipping it to some folder on your desktop. Next, open the IIS manager and create a new application in the
default website named Twitter2 that points to the folder you unzipped the demo application. Finally, test the demo application by firing up your web browser and
http://127.0.0.1/Twitter2. You should see the welcome page (
Default.aspx) of the demo application. If you do, go ahead and try signing in
with your Twitter account and making a tweet. If you get an error message of some sort you'll need to figure out what's wrong and fix this before using the demo application.
Finally, if you create your own Twitter application to test with don't forget to update the consumer key and consumer secret in the
Like many social networking websites, Twitter offers a rich API for integration. Previously, Twitter offered two schemes for authentication: basic and OAuth. In June 2010 Twitter will stop supporting basic authentication and require all integrating applications to use OAuth. Twitterizer version 2.0 is an open-source library for integrating with Twitter that supports OAuth. This article (and its accompanying demo) showed how to use Twitterizer to view the latest tweets in an ASP.NET website, along with how to post a tweet from a website.