Application Authentication Example

Application Authentication is the easiest way to get started with the Twitter API, and it is relatively straightforward to use.  The authentication process consists of two steps:

  1. First, you need to get a token for your app to use, and
  2. Second, you need to configure Twitter4J to use that token.

There is a bit of redundancy in that process, but it’s fairly simple. I encapsulate the first step in its own method, as there is some error handling I’d like to isolate.  The example version of that code looks like:

public static OAuth2Token getOAuth2Token()
{
	OAuth2Token token = null;
	ConfigurationBuilder cb;

	cb = new ConfigurationBuilder();
	cb.setApplicationOnlyAuthEnabled(true);
	cb.setOAuthConsumerKey(CONSUMER_KEY);
	cb.setOAuthConsumerSecret(CONSUMER_SECRET);

	try
	{
		token = new TwitterFactory(cb.build())
			.getInstance().getOAuth2Token();
	}
	catch (Exception e)
	{
		System.out.println("Can't get OAuth2 token");
		e.printStackTrace();
		System.exit(0);
	}

	return token;
}

There’s no reason the method needs to be static, for what it’s worth.  The code starts by creating a Twitter4J ConfigurationBuilder object, which is set to Application Authentication mode.  Next, the consumer key and secret for the application (which is going to be unique to your application) is passed into the builder object.  Finally, we call Twitter to get the authorization token for the application.  Because it’s possible to get an error (very possible, if your consumer key or secret are wrong), we need to handle an error.  The sample code just exits the program; you may wish to do something fancier.

Once you have the token, you can then use it to create your twitter object for follow-on API access.  The code for that looks like:

OAuth2Token token;
token = getOAuth2Token(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setApplicationOnlyAuthEnabled(true); cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuth2TokenType(token.getTokenType()); cb.setOAuth2AccessToken(token.getAccessToken()); Twitter twitter = new TwitterFactory(cb.build()).getInstance();

We get the token from the method defined above, and then build a Twitter4J configuration that uses the token to authenticate our subsequent calls.

For the complete example (including code that does a simple search), download this sample application: ApplicationAuthentication.java

Leave a Reply