If you are building a twitter client of any sorts you should know that basic authentication (user ID and password) will be removed from the twitter API August 16, 2010 (it says so on the twitter API wiki). Instead, Oauth should be used to login.

Why do we need to use Oauth?

One problem with allowing users to build applications towards your service using regular authentication is that these need to use regular login credentials to access data. These third party applications have access to user ID and password and will often store these locally in one way or the other. This is a huge problem for security since you have no control over users credentials.
This is where OAuth comes into play. Oauth grants third-party applications access to the resources without sharing passwords.
If you want to know more about Oauth go to The Authoritative Guide to OAuth 1.0 at Hueniverse.

How to login to twitter with OAuth

Before we start, if you have any problems whatsoever please leave a comment and I’ll try to help you.
Authentication with OAuth in twitter is done in two steps. The first step sends the user to a twitter URL where the user logs in and receives a pin code.
In the second step the pin code is entered in the third party application and a request is sent to grant access to twitter.
Using python this solution is not that well documented. Especially if you, like me, are using the python twitter API mappings to help out with those twitter API calls. If you are planning to build a twitter client using python, don’t be discouraged, python twitter works really well. I will try to make the steps you need to take as clear as possible in this post.
If you never built an application using Python before, check out our guide to GUI programming using Python. Lets get started!

Register your application in Twitter

Twitter client registration


To use Oauth towards twitter your client needs a consumer key and a consumer secret. You get these by going to twitter and registering your application. This is done to the right in the settings -> connections dialog at the twitter site.
Your Key and Secret will be available after registration.

Get Python Twitter

Download Python Twitter Bindings


Python Twitter a is set of twitter API mappings for Python. As far as I know it is the best one to date if you are using python to communicate with twitter. If you want to check out other ones check out the post: Python Twitter API Library Reviews and Samples. I suggest you download the latest source (twitter.py) but it should work if you download the latest package aswell. I think the only thing you need aside from the twitter.py file is to have simplejson installed. If you have other problems there is a nice set of installation instructions at the python twitter site.

Get and install OAuth

Download and install OAuth


Download Oauth from this google code svn path and install it. I simply put the OAuth directory amongst my referenced libraries.

Get and install Oauth Python Twitter

Download and install Python Twitter Oauth


The oauth-python-twitter instructions are not crystal clear. So, to make this easy, lets take this part step-by-step:
Download the oauth-python-twitter library, called oauthtwitter.py,
Before we can start using this oauthtwitter.py needs to be modified. First thing we need to change the imports from

import simplejson, oauth

To

import simplejson
import oauth.oauth as oauth

Then we need to change the getAccessToken() method so that it takes the pin code that will be returned from twitter.
Change from

    def getAccessToken(self, url=ACCESS_TOKEN_URL):
        token = self._FetchUrl(url, no_cache=True)
        return oauth.OAuthToken.from_string(token)

To

    def getAccessToken(self, pin, url=ACCESS_TOKEN_URL):
        token = self._FetchUrl(url, parameters={'oauth_verifier': pin}, no_cache=True)
        return oauth.OAuthToken.from_string(token)

Now the oauthtwitter.py script can be put amongst your referenced libraries and used.

Use Oauth Python Twitter

The Oauth towards twitter is done in two steps. First a request is made fetching a twitter URL where the user needs to allow your twitter application to access the twitter account. A pin code is received that needs to be entered in the next request.
In the second step the user’s pin code is used and a request for access is made from the application.
Both these steps need your consumer key and secret that you got from twitter when you registered your application. Lets see how the code looks for these steps!
OauthRequest.py

from oauthtwitter import OAuthApi

class OauthRequest():
    CONSUMER_KEY = "XXXXXXXXXXXXXXXXXX"
    CONSUMER_SECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
    REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'

    def GetRequest(self):
        vOauthApi = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET)
        self.mOauthRequestToken = vOauthApi.getRequestToken(self.REQUEST_TOKEN_URL)
        self.mOauthRequestUrl = vOauthApi.getAuthorizationURL(self.mOauthRequestToken)

This is the request. It sends the consumer key and consumer secret, that you got when registering your application, to twitter and returns a returns a OAuth Request Token and a authentication URL.
You will need mOauthRequestToken in your call for access towards twitter and mOauthRequestUrl is the twitter URL you should send the user to for authentication. When the user has accepted your application to gain access to the users twitter account he will get a pin code. This pin code is used in the request from the application to get access. That request is shown below
OauthAccess.py

import twitter
from oauthtwitter import OAuthApi

class OauthAccess():

    CONSUMER_KEY = "XXXXXXXXXXXXXXXXX"
    CONSUMER_SECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ACCESS_TOKEN_URL = 'https://twitter.com/oauth/access_token'

    mPin = ""
    mOauthRequestToken = ""
    mOauthAccessToken = ""
    mUser = twitter.User
    mTwitterApi = ""

    def __init__(self, pOauthRequestToken, pPin):
        self.mOauthRequestToken = pOauthRequestToken
        self.mPin = pPin

    def getOauthAccess(self):
        self.mTwitterApi = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET, self.mOauthRequestToken)
        self.mOauthAccessToken = self.mTwitterApi.getAccessToken(self.mPin)
        self.mAuthenticatedTwitterInstance = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET, self.mOauthAccessToken)
        self.mUser = self.mAuthenticatedTwitterInstance.GetUserInfo()

Here the request token together with the pin code is used to get an OAuth Access Token. That access token is used to get an authenticated twitter api (mTwitterApi) instance and the user information of the user that logged in (mUser). Again, the same Consumer secret and Consumer Key is used as in the previous request.

Re-using the access token

So now you have a authenticated twitter account. Would you like to force the user to go through the same process to log in again? I guess not! The solution is to save the access token for later use. Below are the commands needed to acceive this. I have excluded the part where you save and read the file or put the user information in a database.

vAccessToken().to_string()

To save the access token it probably needs to be a string. This fixes that! Now save it for later use.
When you have read the file it is loaded as a string again, but you will need it as a OauthToken object.

import oauth.oauth as oauth
oauth.OAuthToken.from_string(vAccessTokenAsString)

Good thing the OAuthToken class has a from_string() method. Simply put in your string and badaboom, there is your access token.
Next thing you would want to do is to get that authenticated twitter instance again.

from oauthtwitter import OAuthApi
vAuthenticatedTwitterInstance = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET, vAccessToken)

Now you can use that the twitter instance for all your twitter api calls. vAuthenticatedTwitterInstance.GetFriendsTimeline() gets your timeline.

Conclution

OAuth is a great thing for the end user. It is safer because all of the authentication is used directly towards the source. Also, there is one less place where account information is save. For the developer it is a bit worse than just using username and password. But as a developer you should never save account information that is not encrypted and it might be more of a hassle to do a proper encryption than to use OAuth.
I hope this guide has helped you in implementing your OAuth connection. If you have any questions what so ever please leave a comment here and I will reply as soon as I see it!


  • http://www.popdevelop.com Johan Brissmyr

    This article will really come in handy when in need of Twitter authentication. Some clients will need to update their Twitter login when the old method becomes obsolete and this guide gives a good introduction as well as actual code examples.

  • Raman

    Can you please exlain how to use the pytho-twitter package after the authentication is complete.
    Python-twitter examples are all based on username pwd authentication. It will be a great help if you can explain with one example.

    Thanks
    Raman

  • http://mikaelhalen.com Mikael Halén

    Hi Raman, thanks for posting the comment. You are correct in that it is hard to find a good examples on how to use python twitter and login using OAuth. That was part of why I wanted to share this article. I will try to update it so that it covers some more of the python twitter part so that it is more comprehensive.

  • Raman

    Thanks Mikael waiting for your reply.

  • http://yorik.uncreated.net Yorik

    Hi Mikael,
    Thanks a lot for this very detailed info. I just upgraded my little home-made python app to the new twitter authentication system, and this post made it all easy.

    For who is interested in an example, here it goes:
    http://yorik.uncreated.net/scripts/fluxtwitter.py

  • http://mikaelhalen.com Mikael Halén

    It’s great to hear that this guide helped you Yorik! Thanks for leaving a comment about it and showing an example!

  • gprx

    I consistently get a HTTPError: HTTP Error 401: Unauthorized when I try to execute the line

    mOauthRequestUrl = vOauthApi.getAuthorizationURL(mOauthRequestToken)

    my consumer key and secret is correct. Anyone run into this ussue?

  • Hari

    I am developing an application in android using python , when will the user will add credentials (username and password).

  • Pinkerton

    Hi

    I found the article very interesting and useful but I’m a bit lost regarding the second step. What is the PIN and how it can be obtained?

    Is it introduced by the user personally? How does the user introduce her credentials?

    Many thanks

  • Srinivas Kunadaram

    I am getting oauth_token and oauth_token_secret but i get HTTP error 401 when user logs in and authorizes app on callback URL ..
    i am unable to fetch oauth_verifier.
    plz help…

  • Rembspam

    Many thanks for your examples and explanations.

    I do have a question about oauth. Suppose I’m just distributing a standalone Twitter client not related to web or hosting services, to any user who likes to work with it. He will be in control over his userid and password to get access to his Twitter account using my standalone Twitter client installed on his local desktop.

    My question is about getting the PIN code. You state : –You will need mOauthRequestToken in your call for access towards twitter and mOauthRequestUrl is the twitter URL you should send the user to for authentication–

    Can my application fetch that PIN code or does it need to be done via a webbrowser I start . The webbrowser in between sounds not user friendly and makes it more complicated.

    I’m I right that an Internet browser must be used by the user to enter the PIN code on the Twitter website using the URL that the API sent me?

    Best regards
     

  • Pooja Bhurke

    this was a very useful post. I do have a query, what if I’m asking the user to input the twitter pin manually? what would be the process to retrieve information from the site then?
    Thanks
    Pooja

  • Matthewchen Cpa

    could you give me template part? I do not know how to build HTML part 

  • http://www.facebook.com/tommy.pan8331 Tommy Pan

    I’m quite a rookie in Python. I found a script basically is simple version of yours. Although, It returns error after i type in the pin code. I have no clue what’s going on. Regarding your code. Could you give an example for how to put your code together for real utilize please? Many thanks.