About the Author

Chris Shiflett

Hi, I’m Chris: entrepreneur, community leader, husband, and father. I live and work in Boulder, CO.

Twitter OAuth

This post is a quick walkthrough of implementing Twitter OAuth, complete with a working demo.

I've been working on a project with my Analog friends that might use the Twitter API to streamline stuff like signup for those who already use Twitter. Because this now requires OAuth, I needed to implement OAuth quickly, so that we had something to test and consider.

As with all things related to developing with Twitter, my first step was to seek advice from my good friend Ed Finkler. Without hesitation, he recommended a PHP library developed by Abraham Williams, so I tried it out. A few minutes later, I had it working. Follow along, and I'll show you how.

First, download the library. (I used the latest version, 0.2.0-beta3.) Abraham has some handy documentation, but I learned everything I needed from the sample implementation he bundles with the download.

Before you can get the sample implementation working, you need to get yourself a consumer key and consumer secret. Twitter has a page where you can manage your existing apps or register a new one.

If you're completely new to all of this, you may not understand everything Twitter is asking for. Don't worry, because you can edit this stuff later. Also, the callback URL is something that you can override in your code.

Once you have the library downloaded and your app registered with Twitter, you're ready to write some code. Before you do, I think it's a really good idea to try to get the sample implementation working. To do this, edit config.php to define the consumer key and consumer secret you got from Twitter. The callback URL just needs to be a working URL for the included callback.php. With the configuration updated, you should be able to try it out.

Getting it working quickly is fun, but the real fun is doing something useful. For years, I've used OpenID on this blog for authentication. I am strongly considering replacing it with Twitter OAuth. To do so, I just need is to be able to verify that someone is who they say they are on Twitter.

When you're using OAuth, keep in mind that you're just replacing the standard procedure of authenticating with a username and password on your own site. Everything else remains unchanged. For my demo, I check to see whether $_SESSION['access_token'] is set to determine whether the user is signed in. If the user is not, I display a simple button that links to redirect.php. My version of redirect.php is a lot like the one that comes bundled with the library, with the important steps being:

// 1. Get request token.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
// 2. Keep the request token in the user's session.
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// 3. Redirect the user to Twitter for authorization.
$url = $connection->getAuthorizeURL($request_token['oauth_token']);
header("Location: {$url}"); 

After you redirect the user to Twitter, the user decides whether to grant you access:

Twitter then returns the user to the URL you indicate as your callback URL. This is where you can request an access token:

// 4. Get access token.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$_SESSION['access_token'] = $connection->getAccessToken($_GET['oauth_verifier']);
// 5. Discard request token.

At this point, you have the OAuth Holy Grail, the access token. As long as the user does not revoke your access, this access token lets you perform API calls on behalf of the user. You should store the access token, as recommended by Twitter:

Whatever your storage system may be, you'll need to begin storing an oauth_token and oauth_token_secret (collectively, an "access token") for each user of your application. The oauth_token_secret should be stored securely. Remember, you'll be accessing these values for every authenticated request your application makes to the Twitter API, so store them in a way that will scale to your user base. When you're using OAuth, you should no longer be storing passwords for any of your users.

Using the access token is simple:

$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

With this $connection object, you can make API calls with a very simple and convenient syntax. For example, to use account/verify_credentials to verify the access token and get the user's profile information, this is all you have to do:

$info = $connection->get('account/verify_credentials');

The $info object has all the info you need to display the user's profile, like I do in my demo:

<h2>Your Profile</h2>
<p><a href="http://twitter.com/<?php echo $info->screen_name; ?>"><img src="<?php echo $info->profile_image_url; ?>" /></a>
<p><?php echo $info->name; ?></p>
<p><?php echo $info->location; ?></p>
<p><a href="<?php echo $info->url; ?>"><?php echo $info->url; ?></a></p>
<p><?php echo $info->description; ?></p>

To determine whether the user is following me on Twitter, this is all I have to do:

$follows = $connection->get('friendships/exists', array('user_a' => $info->screen_name, 'user_b' => 'shiflett'));

There's a lot more you can do with the Twitter API, but this covers most of my needs for now, and hopefully it helps you get started. Now it's time to get back to work. :-)

About this post

Twitter OAuth was posted on Thu, 16 Sep 2010. If you liked it, follow me on Twitter or share:


1.Lance said:

When the session expires, or the user signs out of your application, do you have to take the user through the whole OAuth process from the beginning next time they want to sign in?

Fri, 17 Sep 2010 at 18:14:00 GMT Link

2.Chris Shiflett said:

Hi Lance,

I asked Ed the same question, and he says the access token does not expire. This aligns with Twitter's suggestion that you should store it. With a valid access token, you don't need to authenticate the user again.

For my Twitter OAuth demo, I use a cookie called refresh to restart the session if it has timed out, but I just use the same access token indefinitely.

Fri, 17 Sep 2010 at 18:31:04 GMT Link

3.Lance said:

Say they're on a public computer and want to sign out permanently. When they return, you'd either have to OAuth reauthenticate them from the beginning, or have your own application specific authentication system, right? I'm just curious what scenarios Twitter's "you don't need to store user passwords" may/may not take into account.

Fri, 17 Sep 2010 at 18:56:42 GMT Link

4.Chris Shiflett said:

When they return, you'd either have to OAuth reauthenticate them from the beginning, or have your own application specific authentication system, right?

Right. You could destroy their session and keep their access token, but in order to determine they're the rightful owner of the access token in the future, you'd need to either have your own account for them that they can use to authenticate, or you'd have to go through the OAuth process again.

Fri, 17 Sep 2010 at 20:34:02 GMT Link

5.Paco said:

Can you post full source code for you demo to download?


Sat, 18 Sep 2010 at 12:45:39 GMT Link

6.Raymond Kolbe said:

Just for some perspective, a while back I implemented Twitter and OAuth using the Zend Framework only. I had to implement a small workaround (which is slick) because Zend's Twitter client only supported Basic Auth at the time.

Check it out: http://www.raymondkolbe.com/2009/10/03/zend-twitter-and-oauth-made-easy/

Sat, 18 Sep 2010 at 14:08:16 GMT Link

7.Kerem said:

So, what about sending twits to twitter without user redirection, just using ajax methods behind the site.

Previously, it was very simple like this;

curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=$status");

But now, it's really complicated even it doesn't need...

Mon, 20 Sep 2010 at 17:39:23 GMT Link

8.pokoot said:

Hi Chris,

Very quick question.

How would you use TwitterOAuth without having a callback URL?

I am implementing this api on a mobile app. I a basically setting the Application Type to Client on dev.twitter.com (So there is no callback URL).

Any thoughts?

Wed, 22 Sep 2010 at 02:44:45 GMT Link

9.Abraham Williams said:

@pokoot: Set your application type settings to "client" on http://dev.twitter.com/apps

Thu, 30 Sep 2010 at 21:39:13 GMT Link

10.Abraham Williams said:

@Kerem: It is still that simple. Here is a three line script to post a tweet: http://gist.github.com/564882

Thu, 30 Sep 2010 at 21:41:52 GMT Link

11.John Thompson said:

this is very intriguing to be honest. might be what i'm looking for

Sat, 21 Jan 2012 at 00:05:46 GMT Link

Hello! What’s your name?

Want to comment? Please connect with Twitter to join the discussion.