Twitter Authentication

September 7, 2010

I have a web app that posts updates to twitter when events happen. This has recently stopped working because twitter have removed basic authentication, and now require the use of oauth.

Here's the steps I took to migrate from

lAuth = tweepy.BasicAuthHandler(settings.TWITTER_USERNAME, settings.TWITTER_PASSWORD)

to using OAuth:

lAuth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_TOKEN, settings.TWITTER_CONSUMER_SECRET)
lAuth.set_access_token(settings.TWITTER_ACCESS_TOKEN_KEY, settings.TWITTER_ACCESS_TOKEN_SECRET)

Register Application

Go to https://twitter.com/apps and register the website that needs to post updates. Once this is complete, you'll have a Consumer Key and a Consumer Secret. These are the strings you need.

Allow API Access to Twitter

At an interactive shell, run the following commands, where CONSUMER_KEY and CONSUMER_SECRET are the strings picked up from your earlier application registration.

>>> import tweepy
>>> lAuth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
>>> lRedirectUrl = lAuth.get_authorization_url()
>>> lRedirectUrl
'http://twitter.com/oauth/authorize?oauth_token=TOKEN'

Visit this url in a browser, and you'll be asked to confirm that you want to allow access to this application. Click Allow.

This will redirect you back to your website, with an additional GET parameter, oauth_token. You'll need the value of this in a moment.

Create Access Token

We now need to create an access token. This won't expire, so we can store this in our django settings.py and use it on all subsequent calls.

Back to the interactive python shell, and run the following commands, where OAUTH_TOKEN is the value of the GET parameter from earlier (just the bit after the equals).

>>> lAccessToken = lAuth.get_access_token(OAUTH_TOKEN)
>>> lAccessToken
<tweepy.oauth.OAuthToken object at 0x196ef90>
>>> lAccessToken.key
'125675646-SNIP'
>>> lAccessToken.secret
'gwMDFdf3r3dIXFxB-SNIP'

These last two values are the ones you need to record in Django settings.py.

Update Application Login

We can now update the application code to login using OAuth rather than username password. We'll need four things - the consumer key and consumer secret from the application we created on twitter, and the access token key and secret from the interactive python settings. Here's the code that replaces the BasicAuthHandler line:

lAuth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_TOKEN, settings.TWITTER_CONSUMER_SECRET)
lAuth.set_access_token(settings.TWITTER_ACCESS_TOKEN_KEY, settings.TWITTER_ACCESS_TOKEN_SECRET)