Twitter4J – quick fix for 401 issues

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 (https://dev.twitter.com/docs/auth) 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 :)

  1. interesting findings, on the other hand no machine connected to the net should be running without ntp synchrinisation :-)

  2. I do find it very strange that ntpd isn’t installed by default in Ubuntu

  3. Really helpful post.
    I did this workaround and one more important thing is you must use twitter4j 3.0.3 jar.
    And you are set to Twitt from Android App.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>