Accessing social networking Web sites through OAuth, Part 1: Build an OAuth-enabled desktop Twitter client

Introduction

OAuth is an open protocol that enables users to share their protected resources among different Web sites, without risking exposure. OAuth is an ideal candidate for mashing up today's social networking Web sites like Twitter. The first part of this series gives an introduction to OAuth, followed by an example of the development of an OAuth-enabled desktop Twitter client. The second part of this series demonstrates how to develop an OAuth-enabled Web Twitter client, which will be migrated to Google App Engine (GAE) in the third and final part of the series.

Xiaobo Yang, Enterprise Java Developer, UK

Xiaobo YangXiaobo Yang is an enterprise Java developer working in the United Kingdom. He is interested in enterprise information systems, in particular, enterprise portals. Xiaobo holds a PhD degree in aerospace engineering from the University of Glasgow.



05 January 2010

Also available in Chinese Russian Japanese

Social networking is widely used by people all around the world. Web sites like Facebook and Twitter are getting more and more people involved, but unfortunately these Web sites are similar to isolated islands scattered in the ocean, given that communication among them is hard to achieve. Although many of these sites are providing APIs to expose some of their data, it is not scalable for a mashup site to aggregate many of such Web sites. For example, management of user accounts for different Web sites is necessary, and some level of single sign-on (SSO) is required to provide a better user experience. Users may be uncomfortable with providing their passwords to a third-party Web site.

This series of articles introduces OAuth, an open protocol which enables users to share their private data between different Web sites along with their credentials, but only expose the data on the original Web site where it is held. This first article will give an introduction to OAuth, followed by an example of a desktop application that allows users to update their Twitter status using OAuth. Part 2 in the series will demonstrate how to develop a more practical OAuth-enabled Twitter Web client. The final article will guide you through how to deploy the Web application developed in Part 2 to the Google App Engine (GAE).

To follow this article, you should be familiar with Web development using Java™ Servlet/JSP. Apache Tomcat has been selected as the Web container, and all development work has been carried out using Eclipse. However, you should be able to adapt the information to your favorite tools. Notice that JDK 5+ is required to compile the source code.

Introduction to OAuth

The OAuth protocol allows users to share private resources stored on one Web site with other sites without exposing the users' credentials—for example, usernames and passwords—to Web sites other than the one holding the users' data. A Web site adopting OAuth as one of its authentication protocols will enhance the privacy and security for users. There are three key players in OAuth: user, consumer, and service provider (see sidebar). A typical OAuth scenario can be described as follows. (For a full description of OAuth, please refer to the OAuth Core 1.0a specification and the beginner's guide in the Resources section.)

  • User: an individual who has an account with the service provider.
  • Consumer: a Web site or application that uses OAuth to access the service provider.
  • Service provider: a Web application that allows access via OAuth.

Web site PHOTO (service provider) holds some private photos of a user (user). But this site does not provide a print service. So when the user wants to print his or her photos, he or she may go to the Web site PRINTER (consumer), which provides a print service. But Web site PRINTER does not have the user's photos. Therefore there must exist data flow from site PHOTO to PRINTER. This is where OAuth can help. If site PHOTO allows authentication using OAuth, then when the user wants to print photos (held on site PHOTO), site PRINTER will redirect the user to site PHOTO to grant it access to the user's photos. Here this user may be authenticated using a normal username-password pair. After the user is authenticated by site PHOTO, he or she may be prompted to give permission to site PRINTER for reading the photos. (Permission may be pre-set so this step can be skipped.) When this is done, the user will be redirected to site PRINTER. Now site PRINTER has permission to read the user's photos from site PHOTO and will be able to print that user's photos on demand. In all the steps, site PRINTER does not know the user's credentials for logging into site PHOTO. This way the user's privacy is better protected. Figure 1 illustrates the above process in a simplified sequence flow diagram.

Figure 1. OAuth interactions among user, consumer, and service provider
A diagram shows the 12 steps of interaction betwen User, Consumer and Service Provider.

(Click to see a detailed description of this figure.)

OAuth Core 1.0 was finalized at the end of 2007. At the time of this article, the latest release is 1.0a, which fixed a security issue about session fixation attacks against the OAuth request token approval flow. Today OAuth has been adopted by major Internet players such as Google and Yahoo.

Development of a desktop client for Twitter

Twitter, one of the most successful examples of social networking, has attracted a large number of users. Not only people, but also companies are using Twitter to quickly update their status. For example, IBM developerWorks is using Twitter to tell people what's new on its site. It is not surprising to find out that Twitter supports OAuth, so I will explore it in this article. I will first show you how to develop a simple desktop client for Twitter using OAuth. If you do not have a Twitter account yet, go to http://twitter.com to register one before you continue reading this article.

Register your desktop application with Twitter: MyTtDesktopClient

Currently Twitter supports two kinds of authentication: Basic Auth and OAuth. While Basic Auth is simple to use, usernames and passwords are not protected during HTTP transportation, so I am not going to talk about it in this article. Before you can use OAuth with Twitter, you need to first register your application at http://twitter.com/oauth_clients. I registered my application with the information shown below.

  • Application Name: MyTtDesktopClient
  • Description: A desktop Twitter client using OAuth
  • Application Website: input your application's home page here
  • Application Type: Client - we are going to develop a desktop client
  • Default Access type: Read & Write - we want to give users write access
  • Use Twitter for login: No - we are not going to use Twitter for authentication

Notice that you need to choose application type as Client, not Browser. (In Part 2 of this series, I will show you a Web-based example.) Also remember to grant the Read & Write access, otherwise your application can only read from Twitter.

If your registration is successful, you will get a consumer key, a consumer secret, and three URLs (the request token URL, access token URL, and authorize URL). Now you are ready for real work.

Develop and test MyTtDesktopClient

I am going to use Twitter4J, an open-source Java library for TwitterAPI (see Resources). Twitter4J wraps many functions so we can focus on our logic without touching the low-level API calls to Twitter. An extra benefit of Twitter4J is that it supports OAuth, which will greatly alleviate our development work. Let's start from the updateStatus(String status) method of class myttdesktopclient.OAuthTwitterClient in Listing 1. The source code is available in the Download section below. Do not forget to put your consumer key and secret (remember these parameters were provided by Twitter when you registered your client) inside OAuthTwitterClient.java.

Listing 1. The updateStatus(String status) method of class myttdesktopclient.OAuthTwitterClient
public void updateStatus(String status) throws TwitterException, IOException {
	Twitter twitter = new Twitter();
	twitter.setOAuthConsumer(consumerKey, consumerSecret);
	RequestToken requestToken = twitter.getOAuthRequestToken();
	AccessToken accessToken = null;
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	while (accessToken == null) {
		System.out.println("Open the following URL and grant access to
	       								your account:");
		System.out.println(requestToken.getAuthorizationURL());
		// Copy the authorisation URL in your browser
		// http://twitter.com/oauth/authorize?oauth_token=xxxxxxxxxxxxxxxxxxxxxxxx
		// Log in Twitter, grant access
		// Get a PIN returned, e.g., 738805
		// Notice you can use HttpClient to do the job above
		System.out.println("Copy the PIN displayed in your browser, then
		       							hit ENTER: ");
		String pin = br.readLine();
		accessToken = twitter.getOAuthAccessToken(requestToken, pin);
	}

	// Persist the access token for future reference
	int userId = twitter.verifyCredentials().getId();
	storeAccessToken(userId, accessToken);
	Status twitterStatus = twitter.updateStatus(status);
	System.out.println("Successfully updated the status for user with ID "
				+ userId + " to [" + twitterStatus.getText() + "].");
}

The updateStatus(String status) method first constructs a Twitter object, and then sets the consumer key and secret. After that, a request token is retrieved from Twitter. The method then prints out the URL for the user to authorize access to his or her data stored on Twitter. Now copy and paste the URL printed by the code in your browser, and hit the Enter key, and you will be asked to authorize the request from MyTtDesktopClient (see Figure 2). Notice that here you are going to authorize on Twitter's site, and our desktop client is unaware of how authorization is carried out.

Figure 2. Grant access to MyTtDesktopClient
Screenshot of Twitter requesting permission to grant access to MyTtDesktopClient, with blanks for the username and password with Deny and Allow buttons.

If you authorize the request, a PIN will be returned by Twitter, as shown in Figure 3.

Figure 3. Twitter returns a PIN to MyTtDesktopClient
A screenshot showing Twitter returning a PIN to MyTtDesktopClient, which is a 7-digit number.

Now copy and paste the PIN into the terminal in which your code is running and hit the Enter key, and you should see output similar to Listing 2. As you can see from Listing 1, the desktop client only cares about the output of the authorization process. If it is successful (in this case, the PIN returned by Twitter), it will get an access token with which the client can update the Twitter status on the user's behalf. This is the key for OAuth, and the user's secrets (username and password) are not exposed to MyTtDesktopClient. If you log onto Twitter, you will see your latest update, "Studying OAuth" (see Figure 4). Notice that the message below your latest status indicates that it was updated by MyTtDesktopClient.

Listing 2. Output of MyTtDesktopClient
Open the following URL and grant access to your account:
http://twitter.com/oauth/authorize?oauth_token=matzsp0Q8k5GfhX2DQoQaHEipBH3g3ieqzPg5QyYek
Copy the PIN displayed in your browser, then hit ENTER:
1944867
Storing access token for 23741179...Done
Successfully updated the status for user with ID 23741179 to [Studying OAuth].
Figure 4. Twitter status updated by MyTtDesktopClient
Screenshot shows the Twitter status updated by MyTtDesktopClient

Notice that in Listing 1, before the Twitter status is updated, the access token is saved by calling the storeAccessToken method. This is because currently an access token from Twitter does not expire. Therefore there is no need to grant access again if a returned user uses our client. This improves the user experience. In this example, the access token is stored in a plain text file for the user. It can be retrieved for future usage. Take a look at the storeAccessToken and loadAccessToken methods in the source code (available in the Download section). A new update method called updateStatus(int userId, String status) makes use of the saved access token (see Listing 3). In the main method, comment out the line tt.updateStatus("Studying OAuth");, and uncomment the line tt.updateStatus(23741179, "Studying OAuth again");. Replace 23741179 with your own Twitter ID. Re-compile and run the code, and you will find your Twitter status is updated without the authorization process described above.

Listing 3. The updateStatus(int userId, String status) method of class myttdesktopclient.OAuthTwitterClient
public void updateStatus(int userId, String status)
		throws TwitterException, IOException {
	Twitter twitter = new Twitter();
	twitter.setOAuthConsumer(consumerKey, consumerSecret);
	AccessToken accessToken = loadAccessToken(userId);
	twitter.setOAuthAccessToken(accessToken);
	Status twitterStatus = twitter.updateStatus(status);
	System.out.println("Successfully updated the status for user with ID "
			+ userId + " to [" + twitterStatus.getText() + "].");
}

Summary

In this first article of the series, I've introduced the OAuth protocol. With the sample application, MyTtDesktopClient, we see the basic elements of using OAuth. The special feature here is that a user's service provider's credentials (Twitter username and password) are not exposed to the consumer, MyTtDesktopClient. In Part 2 of the series, I will demonstrate how to develop a more practical Web application that enables users to communicate with Twitter through OAuth.


Download

DescriptionNameSize
Source codeoauth-part1-source-code.zip3KB

Resources

Learn

Get products and technologies

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=458147
ArticleTitle=Accessing social networking Web sites through OAuth, Part 1: Build an OAuth-enabled desktop Twitter client
publish-date=01052010