Using OAuth to Talk to the Twitter Server with Your Android App

By Barry Burd

The code in your Android app has to talk to Twitter on your behalf. And normally, to talk to Twitter, you supply a username and password. But should you be sharing your Twitter password with any app that comes your way? Probably not. Your password is similar to the key to your house. You don’t want to give copies of your house key to strangers, and you don’t want an Android app to remember your Twitter password.

So how can your app post a tweet without having your Twitter password? One answer is OAuth, a standardized way to have apps log on to host computers.

The big, ugly strings in this code are OAuth strings. You get strings like this from the Twitter website.

Twitter twitter;
// … Some code goes here
ConfigurationBuilder builder =
new ConfigurationBuilder();
builder
.setOAuthConsumerKey(“01qedaqsdtdemrVJIkU1dg”)
.setOAuthConsumerSecret(“TudeMgXgh37Ivq173SNWnRIhI”)
.setOAuthAccessToken(“1385541-ueSEFeFgJ8vUpfy6LBv6”)
.setOAuthAccessTokenSecret(“G2FXeXYLSHI7XlVdMsS2e”);
TwitterFactory factory =
new TwitterFactory(builder.build());
twitter = factory.getInstance();

If gobbledygook of the kind you see here is copied correctly, your app acquires revocable permission to act on behalf of the Twitter user. And the app never gets hold of the user’s password.

Now, here come the disclaimers:

  • OAuth works, and is safer than using ordinary Twitter passwords, but it’s too complicated to explain why here.

  • True app security requires more than what you see in the code above.

    For more comprehensive coverage of OAuth, visit oauth.net: the official website for OAuth developers.

  • The codes in the above example don’t work.

    You must create your own set of OAuth keys and copy them into your Java code.