Simply OAuth-ing for Twitter


All right, I am the hottest twitter application called TweetDekk (replace it with any hypothetical name) and I want you to give me your twitter username and password so that you can send tweets using me. Sounds scary? May be it was not that scary a year back when Twitter had not moved to OAuth. However, now many of us would not dare to share our actual username and password with a third-party application. That is exactly where OAuth helps you.

You can allow an application to use your account without sharing your account details. It is essentially a simple and secure way for people to give access to an application. In a nutshell, as they say on the OAuth site, giving your email account password to a social network site so they can look up your friends is the same thing as going to dinner and giving your ATM card and PIN code to the waiter when it’s time to pay. OAuth allows you to share your private resources (photos, videos, contact list, bank accounts) stored on one site with another site without having to hand out your username and password.

So case made for Oauth, now how do we go about implementing it for our application with Twitter4j?

Assuming that ours is not a browser application but a client application, we can register the application with twitter using the following link http://twitter.com/apps/new

You would be greeted with a screen like this

Since our application is not a browser-based application, we do not need to specify a callback URL

As soon as we register the application, we get the following page. This has 2 important details

  • Consumer key and
  • Consumer Secret

Now we can use the above details to get the Access Token and the Secret. Let us see how,
To use OAuth, the application should use a twitter login using an access token. In order to get the access token and the access token secret, we will use the following program.

public class TokenManager {

	public static void main(String[] args) throws TwitterException, IOException {
		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer("IQEeAhO7WjXRoIvF2blasA", "Tzp0Qibla0XJwiSMSiwN3flkblaJiFggi1bV1tXY");
		RequestToken requestToken = twitter.getOAuthRequestToken();
		AccessToken accessToken = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (null == accessToken) {
			System.out
					.println("Open the following URL and grant access to your account:");
			System.out.println(requestToken.getAuthorizationURL());
			System.out
					.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
			String pin = br.readLine();
			try {
				if (pin.length() > 0) {63					accessToken = twitter
							.getOAuthAccessToken(requestToken, pin);
				} else {
					accessToken = twitter.getOAuthAccessToken();
				}
			} catch (TwitterException te) {
				if (401 == te.getStatusCode()) {
					System.out.println("Unable to get the access token.");
				} else {
					te.printStackTrace();
				}
			}
		}
		System.out.println("Token is : "+accessToken.getToken());
		System.out.println("Token secret is : " + accessToken.getTokenSecret());
		// persist to the accessToken for future reference.
		System.exit(0);
	}
}

Note that when you run this program with the correct ConsumerKey and ConsumerSecret you would be prompted to go to a URL and enter a PIN. The URL generated in our case is

Open the following URL and grant access to your account:
http://api.twitter.com/oauth/authorize?oauth_token=LiPJqKttOhUNnbEV4QaR1RUwhmm4c1GZ3dXhZMJt24
Enter the PIN(if aviailable) or just hit enter.[PIN]:

Now once you point the browser to the URL mentioned then you would be getting a screen like this, asking you to validate the application

If you allow the application then you would get a pin like this

Now, this is the PIN which needs to be fed into our program which is helping us to get the access token and access secret key

Open the following URL and grant access to your account:
http://api.twitter.com/oauth/authorize?oauth_token=LiPJqKttOhUNnbEV4QaR1RUwhmm4c1GZ3dXhZMJt24
Enter the PIN(if aviailable) or just hit enter.[PIN]:0834655
Token is : 93580849-ujydrWzwKApblatnCCItxbUJhsu4bladDmmQAZys
Token secret is : h5iyDLrblaJxud8NmoJVaC95cqtxblaaGMTkAaf3c

You can persist this information anywhere you like and use it in your program. For us, since we use twitter4j, we put this in the twitter4j.properties file like this

debug=true
oauth.consumerKey=IQEeAhO7WjXRoIvF2blasA
oauth.consumerSecret=Tzp0Qibla0XJwiSMSiwN3flkblaJiFggi1bV1tXY
oauth.accessToken=93580849-ujydrWzwKApblatnCCItxbUJhsu4bladDmmQAZys
oauth.accessTokenSecret=h5iyDLrblaJxud8NmoJVaC95cqtxblaaGMTkAaf3c

and then twitter4j expects that this file is present on the classpath. Now we can easily start sending tweets using a program like this

public class TwitterService implements SocialService {

	public Object sendUpdate(String string) throws TwitterException {
		Twitter twitter = new TwitterFactory().getInstance();
		Status status = twitter.updateStatus(string);
		return status;
	}

	public Object sendDirectMessage(String receiverId, String message)
			throws TwitterException {
		Twitter sender = new TwitterFactory().getInstance();
		DirectMessage directMessage = sender.sendDirectMessage(receiverId,
				message);
		return directMessage;
	}

Happy Tweeting!

Advertisements

About Vikas Hazrati

Vikas is the Founding Partner @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. Knoldus does niche Reactive and Big Data product development on Scala, Spark and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). To know more, send a mail to hello@knoldus.com or visit www.knoldus.com
This entry was posted in Cloud, Java and tagged , , , . Bookmark the permalink.

One Response to Simply OAuth-ing for Twitter

  1. Pingback: Tweets that mention Simply OAuth-ing for Twitter « Inphina Thoughts -- Topsy.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s