The Belgian Play! Framework User Group is holding its first dojo on Wednesday, and I’m helping to implement the reference application.  We’re using Twitter as a communication point, and one of the best (the best?) Twitter API for Java is twitter4j.  We have an app set up with Twitter, and everything should have been working fine…except we couldn’t post anything.  Which blows, because that’s kind of the point.

The exception thrown every time we attempted to post was a 401 unauthorised exception.  I double-checked the access rights, and it appeared we had granted read-only permission for the app.  I renewedthe access rights with read-write permissions, and it still didn’t work.  Nuts.

The exact error, for reference, was

twitter4j.TwitterException: 401:Authentication credentials ( were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
{"errors":[{"message":"Could not authenticate you","code":32}]}

The problem lay not with the various keys used to authenticate with Twitter, but with the time on my laptop.  Apparently it was out of sync with the Twitter servers, and this was causing the problem – presumably it’s security against some kind of replay attack.  The solution was extremely simple – I installed the ntp daemon to constantly correct my system time.  The instructions for Ubuntu can be found here. To save you a click, the command you need is

sudo apt-get install ntp

I tried posting again as soon as the daemon was installed, and it worked perfectly.

PS If you’re reading this in the dojo, you owe me a beer 🙂

3 thoughts on “Twitter4J – quick fix for 401 issues

Leave a Reply

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