Twitter OAuth on Java AppEngine

After a few struggles I finally managed to authenticate to Twitter using OAuth on AppEngine with Java. After trying out a few other options, I used oauth-signpost - a simple Java OAuth API. Although their desktop application sample worked with no surprises, once I tried the web application, I ran into 401s. The obvious problem was on my Twitter application settings page, I had forgotten to set my application type to 'Browser'. Also, callback URL is required, so I had to use the right APP_ID and CALLBACK.

Then I ran into another problem. In the desktop example, there is one instance of OAuthConsumer, and one instance of OAuthProvider, and they live happily within the main method block. But in the web app, the entire action is split into two parts. First, you have to retrieve a request token and redirect the user to the Twitter OAuth page:

There are two attributes stored in a session, so don't forget to enable sessions in your appengine-web.xml (note that sessions are persisted in datastore):

Second, you need to retrieve the access token with a new request, processing the callback after successful Twitter authentication. But at this stage, if you don't have that earlier created consumer and provider, you need to create them again. But not just create, you need to initialize them to the state they are after retrieving a request token. Simply said, you need to do this:

That's it. Now, you can run your Twitter API queries and hopefully also enjoy announced and increased API rate limits for OAuth in the very near future.

This blog post was verified by