In this article I will introduce you to the Zend_Oauth component of the Zend Framework. This component implements the OAuth standard, allowing users to access protected data on other sites.
To demonstrate how to use this component, we’re going to create a basic script that allows a user to log in to their Twitter account and post a status update. Twitter is currently phasing out “basic authentication” and requiring all third-party web and desktop applications use OAuth.
This article can be used as a starting for creating (or updating existing) Twitter API apps. We will also be using the Zend_Service_Twitter component, as I covered in a previous screencast.
This article requires Zend Framework, downloadable from http://framework.zend.com. At time of writing, the current version of Zend Framework is 1.10.6. There have been many changes recently to how integrates with Zend_Oauth, so using this latest version is highly recommended.
This article also uses Zend_Db to connect with a MySQL database. The pdo_mysql extension must be available on your server for this to work. There isn’t much database access code, so if you require different database access code there are only a few lines to update.
We also make basic use of Zend_Db_Select to build an SQL query, as well as Zend_Session for session management. For more details about Zend_Session read Zend Framework 101: Zend_Session.
There are many guides and diagrams of how oAuth works available online, but to keep things simple, here’s what you need to know for authenticating with Twitter:
- Web application requests an authentication token from Twitter
- Web application redirects user to Twitter
- User signs in to Twitter then authorizes your web application
- Twitter redirects user back to web application with authorization token
- Web application requests access token from Twitter
Assuming each of these steps completes correctly (that is, the user successfully authenticates and then allows your application access), you can then access the Twitter API with their account.
For more details of how this process works (specifically with Twitter), I recommended the following pages:
In the code we will implement in this article we have a protected page that users can only access once they’ve authenticated with Twitter. We will write their access token to a database table so we can use it again in future. Currently there is no expiration date on a Twitter access token.
In order to implement Twitter access with Zend_Oauth we’re going to have three scripts facing our web application:
- The protected script that posts a message on Twitter
- A login script that begins the OAuth authentication process
- A callback script that Twitter redirects to after the user authorizes our application
Additionally, we are going to create a utility script that holds data and functions required in all scripts.
First though, let’s create a database. For the purposes of this article, we need only a single table. This table stores access tokens. As mentioned previously, this article assumes you already have some kind of protected area on your web site, and thus some kind of account identifier that the access token will be linked against.
Listing 1 shows the
twitter_auth database table. The fields needed to make a request on the Twitter API are the
secret fields. You can adjust any other fields as required.
Now we must implement code to access this table. We’ll now set up the entires
globals.php file. The other scripts in this article will make use of this. We’re going to use Zend_Db to communicate with the database.
Listing 2 shows the code to connect to the database with. You can substitute your own database connection details as required.
When you register your Twitter application your are given consumer a consumer key and secret that allows your application to use the platform. Since these values are needed in multiple scripts we’ll now include a function to get the configuration details for Zend_Oauth. You can access these values from within your account on http://dev.twitter.com.
Listing 3 shows the configuration details that we’ll make use of later in this article. The key names for the array are dictated by the
Zend_Oauth_Consumer class. The consumer key and secret
Next I have included a function called
getUserId(), as shown in Listing 4. This is used to return the local ID of the user currently logged-in to your web application. You should update this code to reflect your own application accordingly.
Finally, Listing 5 shows a function to retrieve the access token and secret for the user currently logged-in (based on the ID returned from
getUserId()). If no access token was found an exception is thrown. We’ll use this exception later on the protected script.
In this script we try to retrieve a row from the
twitter_auth table. If a row is found we build an instance of
Zend_Oauth_Token_Access. This is a utility script for Zend_Oauth that is used both when authenticating, but also when using the Twitter API.
Listing 6 shows how all of this code fits together inside
globals.php. We’ll make use of this script in each of the other scripts covered later in this article.
Next we’ll look at the login script. This script gets a request token (whcih we must then store) and then redirects the user to Twitter so they can authenticate.
Another name for a web application to communicates with an OAuth server is a consumer. Likewise, the Zend_Oauth components includes a class called
Zend_Oauth_Consumer. This is the class we use to communicate with Twitter.
In the previous section we created a function called
getAuthConfig(). This function returns a number of configuration options that we pass directly to
Zend_Oauth_Consumer when we instantiate it.
In this section we will create the
login.php script for our basic application. As mentioned previously, the first stage in authenticating with an OAuth server is to get a request token. We can do so using the
Zend_Oauth_Consumer. This method returns an instance of
Once we have a request token we must store it temporarily then redirect the user to Twitter so they can authenticate. Listing 7 demonstrates how we can achieve this.
After retrieving the token, we write the token and secret to session so it is available after the user returns from authenticating at Twitter (we will need it again to complete the process).
The final step is to redirect the user to Twitter so they can authenticate. Calling
redirect() on the consumer object takes care of this for us.
Next we will look at the
callback.php script, which is used to complete the authentication process.
One of the configuration options for
Zend_Oauth_Consumer was a callback redirect URL. This is the URL that the OAuth server (Twitter in this case) redirects the user back to after they’ve authenticated and approved the consumer application.
In our application we’ve called this script
callback.php. In addition to using the request tokens we stored in
login.php, the user is redirected to
callback.php with an authorization token which we use to retrieve an access token from Twitter.
Listing 8 shows how we begin the callback script. We start by ensuring the request tokens exist in the session data. If they’re not the script will fall through and output an “invalid request” message (I’ll include this shortly). We then recreate the
Zend_Oauth_Token_Request object so we can retrieve the access token.
Next we use the
Zend_Oauth_Consumer class to retrieve an access token. To do so, we use the
getAccessToken() method. This method will throw an exception if a valid access token cannot be retrieved, so we wrap this entire block in a “try catch”.
getAccessToken() we pass the request token as well the authorization token that was passed back when the user was redirected. The authorization token is stored in “get” data. Therefore we can simply pass
$_GET, as shown in Listing 9.
At this stage we have an access token with which we can access the Twitter API. We will now write this to our previously created database table (doing so means the
getTwitterAccessToken() will now have data to return). Listing 10 shows how we can write this data.
Finally we must clean up and finish off the request, as shown in Listing 11. To clean up we simply remove the request token and secret stored in the session data. We then redirect the user back to protected script (
index.php – we’ll create this shortly).
Additionally, we’re going to handle the exception that may be thrown by
getAccessToken(), as well as output a message if the session data wasn’t found. Currently the exception handler has been left blank. You can substitute in your own logic (or logging) as required, but otherwise it will just fall through to the error message that is output.
callback.php script is shown in Listing 12.
Finally we will implement the protected page (
index.php). This script allows the authenticated user to post a message to their Twitter timeline.
The final script we must implement in our OAuth example is the protected script. I’ve referred to this as
index.php previously in this article.
If a user has already authenticated with Twitter they will be displayed a form with which they can post a message to their Twitter timeline. If they’re not authenticated they will be redirected to the
login.php script (which in turn will begin the OAuth authentication process).
Earlier in this article we created a function called
getTwitterAccessToken. This function returns an instance of
Zend_Oauth_Token_Access if the user has authenticated with Twitter. If the user has not authenticated an exception is thrown. Therefore we can use this exception to determine whether or not to begin the login process.
Listing 13 demonstrates the basic algorithm for achieving this. We’ll add more code to this shortly.
Next we use the
Zend_Service_Twitter class to post a message to Twitter. If you’re using an API call that does not require authentication, you can instantiate this class then make the API call. However, since our example will post a message to a user’s timeline we must be authenticated.
Since we’ve now authenticated with the Twitter OAuth server we must include details of the access token. The
Zend_Service_Twitter class uses
Zend_Http_Client to perform its API calls, which is fortunate, since
Zend_Oauth_Token_Access has a method
getHttpClient() method which returns an instance of
Zend_Http_Client with the relevant OAuth headers automatically set.
An important thing to realize with this is that when making an API call using OAuth, you must include your consumer key in addition to the access key. We can therefore pass the
Zend_Oauth_Consumer options returned by our
getAuthConfig() method to
Listing 14 demonstrates how to set up
Zend_Service_Twitter. We’ll plug this in to the
index.php script shortly.
Finally, we make the Twitter API call to post a message to our timeline. We’ll submit this message using post (meaning we access the message from
$_POST['message'] – we’ll add the form to submit this value shortly).
Without getting to far into the details of
Zend_Service_Twitter, we call
$twitter->status->update($message) to post a message.
Listing 15 shows this in more detail. It assumes we’ve already retrieved the access token using
To complete this script, let’s piece the previous code together. Listing 16 shows the full
index.php script. In addition to what’s already been covered in this section it also includes a form with which to submit a status update. I’ve also included a
var_dump() of the response from posting a status update.
Now we have a functioning OAuth implementation for Twitter. You can now easily build on the API calls to provide more functionality, both to protected and unprotected API calls.
In this article I showed you how to use the Zend_Oauth component of the Zend Framework by implementing a basic Twitter client.
I showed you how to authenticate using
Zend_Oauth_Consumer, which consisted of these main steps:
- Retrieve a request token from Twitter
- Store the request token and redirect the user to Twitter
- User authenticates and grants your application permission
- You receive an authorization token and request an access token
- Store the access token, then use for subsequent API calls
Additionally, I showed you some “real world” usage of some other Zend Framework components (such as Zend_Db, Zend_Session and Zend_Service_Twitter).
While this implementation was quite basic (and would need various improvements to scale to fully-featured web application), it hopefully demonstrates how simple and useful a service such as OAuth can be.
- http://framework.zend.com/manual/en/zend.oauth.html – Zend Framework manual entry for Zend_Oauth.
- http://dev.twitter.com/pages/auth – OAuth theory and implementation
- http://dev.twitter.com/pages/sign_in_with_twitter – “Sign in With Twitter” details