How to persist OAuth access token for twitter application

Twitter has become become the information hub in the world wide web.Popularity of Twitter is because of its simple user interface with abounding features and galore of APIs.Any developer will agree, Twitter has most varied, efficient and well documented APIs in comparison to other giants of web.This is the reason, there are so many Twitter applications floating around the internet.In this post we’ll check out OAuth work flow and persisting access token fetched from a particular Twiiter account for future use.For this tutorial we’ll using Twitter4j APIwhich has OAuth support and its independent of any other jar.At the end I’ll share the desktop application created for twitter.
What the heck is OAuth ??
OAuth is all about securing credentials in the ever-changing web world. The end-user is not required to hand over the username/password combination to any appliation.Rather, login credential will be handled by the service provider itself.Application will act on behalf of the user depending upon the generated access token by the service provider.End-user can revoke the permission at any time.

So roughly developer doesn’t need to worry about authentication.This headache is solely transferred to the service provider.Bad news for black hats.


So , what will we be doing ??
Let’s go through the following simple work-flow screen

The work-flow screen given above includes  pretty much everything.
1)Each application will have  unique consumer key and consumer secret given by Twitter during application registration.
2)When end-user invokes the application, one authorization url is generated from the request token.
3)User has to authorize the application after accessing that url.
4)After that user will be given one secret pin, which will confirm specific user has granted access to the application.
5)At last Twitter sends access token and access token secret key to the application.

Using token and key pair application will be able to change or update on behalf of the user.Same token / key pair can be stored in database or file system in order to do the required changes without going through full cycle of authorization.

Code Snippet

Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(“[CONSUMER KEY]”,”[CONSUMER SECRET]”);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
}catch (Exception ex){
JOptionPane.showMessageDialog(null,”Error … here is what I know :”+ex.getMessage());
JOptionPane.showMessageDialog(null,”Exiting from the application …”);
System.exit(0);
}AccessToken accessToken = null ;

if (accessToken == null){
String authURL = requestToken.getAuthorizationURL();
/* Here goes code to open authURL
…..
…..
*/
}

String oauth_verifier = JOptionPane.showInputDialog(null,”Enter Twitter Authrization code”,”Authrization”,1);

if (oauth_verifier == null || Integer.parseInt(oauth_verifier) == JOptionPane.CANCEL_OPTION ){
JOptionPane.showMessageDialog(null, “You pressed cancel button. Exiting the application …”,”TwitterApp”, JOptionPane.CLOSED_OPTION);
System.exit(0);
}

try{
if(oauth_verifier.length() > 0){
accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
}else{
accessToken = twitter.getOAuthAccessToken();
}

} catch (TwitterException te) {
if(401 == te.getStatusCode()){
JOptionPane.showMessageDialog(null,”Unable to get the access token.”);
}else{
JOptionPane.showMessageDialog(null,te.getMessage());

}
}

String token = accessToken.getToken();
String tokenSecret = accessToken.getTokenSecret();

Now write these token and token secret into a file or store it in a database.Use the code given below to re-use them

try {
AccessToken accessToken = new AccessToken(token, tokenSecret);
Twitter twf = new TwitterFactory().getOAuthAuthorizedInstance(“[CONSUMER KEY]”,
“[CONSUMER SECRET]”,accessToken);
}catch (Exception exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}

Following is the example to fetch user information

try {
String user = twf.getScreenName().toString(); /* Get screen name */
User usr = twf.showUser(user);
String currentStat = usr.getStatus().getText(); /* Get current status of the user */
URL iconSrc = usr.getProfileImageURL(); /* Get hot link for profile picture */
String usrDesc = usr.getDescription()); /* Get user description */
String loc = usr.getLocation(); /* Location of user */
}catch (TwitterException twfc){
JOptionPane.showMessageDialog(null,”Exception while getting user information “+twfc.getMessage());
}

Following is the example to fetch time line

try {
Liststatuses = twf.getFriendsTimeline();for (Status status : statuses) {
System.out.println(status.getUser().getName() + “:” + status.getText());
statusesListModel.addElement(status);

}

}catch (TwitterException twc){
JOptionPane.showMessageDialog(null,”Exception while fetching time line”+twc.getMessage());
}



Here is a desktop application for Twitter I created using swing framework :

Twitter Application Screen Shot


You can download the application from the link given below :


Requirements for the Application:

JRE 1.6.X


Note:
Please go through the ReadMe.txt for instruction about using the application.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *