Twitter provides an API for developers to build applications on top of it. The API has supported basic authentication over HTTP, but beginning in June 2010 Twitter is discontinuing basic authentication and migrating all Web and desktop applications to OAuth (Open Authorization).
Although simpler to implement, basic authentication had its drawbacks. If your Web application uses basic authentication, your users will have to provide their credentials to get access to your website. Their credentials then will be passed over the network as a clear text -- not a very secure or reliable method of authenticating a user. In addition, this method does not provide a persistent authentication token.
OAuth on the other hand provides a more secure way to authenticate users and allows a persistent access token, which application developers can then consume. For now, Twitter does not allow this authentication token to expire, meaning users do not have to log in every time they use the same application. The token becomes invalid only when a user rejects the application from his or her application settings.
What Is OAuth and How Does It Work?
OAuth (Open Authorization) is an open standard that allows anyone to share resources securely from one site (which supports OAuth) to another third-party website. With OAuth, the user does not have to give his/her credentials to the third-party website.
Figure 1 illustrates how Twitter allows OAuth to access its user details.
If you have a Twitter API-based application, here is how it allows OAuth to access your users' details:
When a user accesses your application, you need his/her details (such as Twitter handle, friends, followers, etc.). To do so, your application sends a request to Twitter and gets a one-time request token, which is then used to create the authorization link.
The user clicks on the authorization link and gets redirected to the Twitter website. When the user logs in, Twitter asks him or her whether it should allow XYZ application to access the user's data.
When the user grants your application access to his or her data, Twitter sends back an access token and an access token secret. Now your application does not require the user's credentials to access his or her Twitter data. All it needs is the access token and the access token secret. You can store these in the database and create a cookie so that whenever the user visits you can recognize that user.
Now that you know what OAuth is and have a fair idea of how it works, let's move ahead.
Getting Started with Twitter OAuth
In this section, we will use Twitter's OAuth API to authenticate an application and interact with a demo application. Follow these instructions to get started:
Register your application at twitter.com/apps. Be sure to give the correct callback URL, because this is where the user will be redirected after a successful authentication. Also take note of the consumer key and consumer secret, which will be provided after registering.
Now that you have successfully registered your application, download the OAuth library and the wrapper class (contained in a zip file). These will help you interact with the Twitter API.
Extract the zip file and you should see the following files.
You first need to configure your application. To do so, open config.php and input the CONSUMER_KEY and CONSUMER_SECRET provided by Twitter when you registered your application. Also, specify the CALLBACK_URL to which Twitter should redirect users after successful authentication. Specifying the URL here will override the one you provided during the application registration process.
Authenticating the User with Twitter OAuth
Now, if you look back at Figure 1, you will notice three steps for successfully authenticating the user. We will complete the steps here.
Get the one-time request token and create the authorization link.
$connection = new TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(CALLBACK_URL);
//temporary store the request tokens in the session vars
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
//this function returns the authorization URL
$authorize_url = $connection->getLoginURL($request_token);
echo "<a href='$authorize_url'>Authorize this app</a>";
The user authenticates the application and Twitter redirects the user to the CALLBACK_URL, which is defined in config.php.
Now get the access token. Use the getAccessToken() function by using the verification (oauth_verifier), which the API appended with the callback URL. When you have the access token, you can play with the API however you want to. The following code shows how to update your status on Twitter.
if($_SESSION['oauth_token'] !== $_REQUEST['oauth_token'])
//token expired get a new one. You can clear session over here and redirect user to the login link
die(token expired get a new one);
$obj = new TwitterApi(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $obj->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
unset ($_SESSION['oauth_token'], $_SESSION['oauth_token_secret'] ,$obj);
$obj = new TwitterApi(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $ obj ->doPost('https://api.twitter.com/1/statuses/update.json', array('status' => 'This is my first update using OAuth.'));
The above code will update your status on Twitter using OAuth.
The complete code is included below, and the README file will get you started. You can use the wrapper class included in the zip file and extend it to build your own applications.
Twitter OAuth will replace its basic authentication, so it is a good idea to migrate all your applications to the new code, if any. You can read about various updates related to the Twitter API on dev.twitter.com.
Sachin Khosla is a Web developer and technology evangelist who has written and spoken extensively about open source technology. Sachin is part of an active open source community that organizes OSScamp in Delhi, India. To learn more about this author, read Sachin's blog at Digimantra.com.