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.

[sourcecode language=”java”]
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);
}
}
[/sourcecode]

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

[sourcecode language=”text”]
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]:
[/sourcecode]

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

[sourcecode language=”text”]
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
[/sourcecode]

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

[sourcecode language=”text”]
debug=true
oauth.consumerKey=IQEeAhO7WjXRoIvF2blasA
oauth.consumerSecret=Tzp0Qibla0XJwiSMSiwN3flkblaJiFggi1bV1tXY
oauth.accessToken=93580849-ujydrWzwKApblatnCCItxbUJhsu4bladDmmQAZys
oauth.accessTokenSecret=h5iyDLrblaJxud8NmoJVaC95cqtxblaaGMTkAaf3c
[/sourcecode]

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

[sourcecode language=”java”]
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;
}
[/sourcecode]

Happy Tweeting!

Written by 

Vikas is the CEO and Co-Founder of Knoldus Inc. 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). Vikas has been working in the cutting edge tech industry for 20+ years. He was an ardent fan of Java with multiple high load enterprise systems to boast of till he met Scala. His current passions include utilizing the power of Scala, Akka and Play to make Reactive and Big Data systems for niche startups and enterprises who would like to change the way software is developed. To know more, send a mail to hello@knoldus.com or visit www.knoldus.com

1 thought on “Simply OAuth-ing for Twitter

Leave a Reply

%d bloggers like this: