OAuth for PHP Twitter Apps, Part 1

As of August 31, Twitter’s HTTP Basic Authenticated API service has been disabled entirely. Now, any interface with the API will be required to use a token-based authentication method known an OAuth.

What does this mean? Anyone who’s written a server-based application that talks to Twitter via its API will need to spend some time upgrading it. In this article, we’ll focus on automated back-end type applications, such as an app that automatically tweets when a new deal is available on a website, a sports score tweeter, or other similar apps. In part II, we’ll have a look at the more traditional OAuth model, where individual users authorize your app to access their Twitter accounts via a web interface.

At first glance, the task of implementing OAuth can appear daunting, and OAuth’s token exchange system can be confusing if you’re unfamiliar with it. Fortunately, there are some rather clever individuals who’ve done the groundwork for us, so let’s get started.

Registering Your App

--ADVERTISEMENT--

Previously, Twitter didn’t require you to register your application. Under OAuth, however, you must do so. When you do, Twitter will provide you with a set of keys that you’ll need to connect your application to the API.

To register your app, visit http://dev.twitter.com/apps and complete the form, most of which is quite straightforward—though there are a couple of fields that may throw you:

Callback URL may be left blank if there’s no requirement for your application to authenticate users via a web interface. In the examples I mentioned above (auto-tweeting features of a website), there’s no login process, so there’s no need to provide a URL to redirect users to.

Default Access type refers to the access your application will have to Twitter. Read-only removes the ability to post tweets or add/remove friends, while Read & Write allows complete access. This is almost certainly what you want for your application.

Application Type should be changed to Client, even though this application may be run by a cron job simulating a web browser hit, or via a behind-the-scenes trigger from your website, a user will never directly interact with it through a browser.

Once your app is registered, you’ll be provided with an OAuth Consumer key and Consumer secret. These two strings are the basis for our OAuth connection.

Download the TwitterOAuth PHP Class

Originally developed by Abraham Williams, TwitterOAuth handles the generation, registration, and authentication of OAuth requests to interface with Twitter. Thanks to this class, it’s unnecessary to understand all the ins and outs of OAuth key and token manipulation. Go ahead and download a copy of the library. For this article I’ll be using version 0.2.0-beta3.

Modify the Class to Allow PIN-based OAuth Registration

Usually, web-based Twitter apps will authenticate with Twitter by passing the user over to Twitter, where they can click on an Authorize button. However, for apps without user interaction (such as the automated Tweet applications given as examples above), we’d rather avoid having to do that. Fortunately, Twitter has provided a PIN-based authentication option intended for desktop applications, but equally suitable for our automated web-based application.

The initial request is authorized by Twitter, and will give you a seven-digit PIN. Your application will then make a request using that PIN, which will provide it with an access token to be used in future requests.

However, the TwitterOAuth class we grabbed above lacks native support for PIN-based registration, so we’ll need to make a quick change to the code to make everything work. This code is based, with some modifications, on this blog post by Konstantin Kovshenin. Edit the file twitteroauth.php and replace the function getAccessToken beginning at line 111 with the following:

Create a Request Token and a Registration URL

Now you need to generate some access tokens for your app. This takes place in two steps: first, you generate some request tokens and a register URL, and then you use those to generate the access tokens. The code you’ll write is only for the purposes of acquiring these tokens, and can be separate from your application. As a result, you can run it from your development or local server.

Once you’ve created the register script you’ll need to run it to request access from Twitter:

Log in to Twitter (via the website) using the Twitter account you want the app to use

Load the register.php file in your browser

The script will create two files in its directory containing your request token and request token secret

A link will display on the screen; this is a link to your registration URL.

Click the link, and Twitter will ask if you’d like to authorize the app to access your account (the one you signed in to in step 1).

Finally, Twitter will display a seven-digit PIN. Copy it down.

Generate Access Tokens

Now that Twitter has authorized our request for access, we need to pass back the provided PIN in order to generate an access token and its secret. Once this is done, our application will never again have to go through this authentication process, and will have permanent access to the linked Twitter account.

This script expects you to pass the PIN as a GET parameter (for example, http://dev.machine/validate.php?pin=1234567), and will save files called access_token and access_token_secret to the folder. Access it in your browser, passing in the PIN.

warning: Time is of the Essence

The request tokens and register URL we generated in the previous step aren’t indefinite: Twitter will expire them after a given time has passed. If you receive errors accessing validate.php, or find that the generated files are empty, it could be because you’ve taken too long to fire up the script.

If this happens, simply hit up register.php again to generate a new PIN.

Tweet Away!

With all of the OAuth tokens done and dusted, it’s time to actually use the API. Let’s try the simplest test possible, and tweet “hello world” from the authorized account:

Put this file in your test directory, and access it via your browser (again, you’ll need to paste in your own consumer key and secret). You’ll see confirmation that your account was connected, and if you now load up the account’s Twitter profile, you should see a “hello world” tweet!

Finally, a Clean-up and Some Security

Now that you’re up and running, the register.php, validate.php, request_token, and request_token_secret files are no longer required for the operation of your app. The access tokens that have been generated now handle all back and forwards between your app and Twitter. You’ll also note that none of the code we’ve written, or in any of the generated files, is there any mention of the linked Twitter account’s user name or password; this is a major security advantage of the OAuth method.

That said, if your access_token and access_token_secret files are in a publicly accessible web directory, the account’s security can still be compromised. Once generated, they should be shifted outside of your server’s web folders, and loaded in with PHP’s file operations. If, for some reason, that’s not an option for you, move them to a subfolder that’s inaccessible via the Web.

Summary

While it’s become a little more complicated up-front to set up an application with access to a Twitter account, there are definite security benefits to the OAuth approach. Once you learn the ropes, it’s quite straightforward to set up new applications with access to a Twitter account.

In part II of this series, we’ll turn our attention to Twitter apps that involve your users individually authorizing their accounts via the Web.