Troubleshooting Twitter API Application Authentication Failures

All developers know the frustration of finding out that once functioning code no longer works. This can happen when your previously-working Twitter API application no longer connects to the Twitter API because of an authentication failure. In this article I’ll show you how to solve a common cause of Twitter API application authentication failures.

If you’re using Twitter4J on the command line, for example, you’ll likely see something like this:

[Wed Jul 08 11:37:49 BST 2015]Establishing connection.
[Wed Jul 08 11:37:50 BST 2015]401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.

This output gives two possible explanations for the failure:

  1. Your application is not using a valid consumer key/secret pair or a valid access token/secret pair
  2. Your system clock is not in sync

Since your application was just working, it’s unlikely that the consumer key/secret pair or the access token/secret pair are at fault but it’s worth checking. You can find the consumer key/secret and access token/secret pairs for your application at apps.twitter.com under the Keys and Access Tokens tab for your application.

I’ve found that a common cause of authentication failure is the system clock explanation: the Twitter API requires that the clock of the system on which you’re running your application must be in sync with Internet time.

Synchronizing your system’s clock is a simple matter of reaching out to an Internet time service. For example, use the following command to synchronize the Ubuntu system clock:

sudo ntpdate ntp.ubuntu.com

After updating your system’s clock, your Twitter API application will probably start working again.