OAuth for PHP Twitter Apps, Part 2

Share this article

In Part 1, we looked at how to implement a server-based application that would run autonomously using OAuth, now Twitter’s only accepted authentication method. In Part 2, we’re going to walk through how to let users log in to your site using Twitter’s “Sign in with Twitter” authentication technique. This in turn will give us access to Twitter’s API.

You may have noticed “Sign in with x” buttons becoming increasingly popular as the number of username and password combinations we’re asked to remember seems to increase at an exponential rate.

The idea of a single login is by no means a new one. One of the most successful implementations is OpenID, which provides a single identity to sign in to multiple sites. It was discussion of this functionality in OpenID that led directly to the development of OAuth, an external site with limited and defined access to users’ sites.

The use of single sign-on methods in popular large-scale applications such as Twitter and Facebook has helped to popularize it as a streamlined way of logging users into your website. And you can leave the worrying to someone else about the security processes involved!

Let’s see how it’s done.

Register Your App

Just as in Part 1, if you want to use Twitter’s API in any form, you’ll have to register an application with their developer service. Go to http://dev.twitter.com/apps and complete the form, taking special care with the following fields:

  • Application Type must be Browser. Interaction between the user and Twitter takes place solely in the browser.

  • Callback URL refers to the PHP file on your server that Twitter will call upon to process the result of a login request. We’re going to create this file and call it callback.php. Remember to also include the server name; for example, http://yourserver.com/twitter/callback.php.

  • Default Access Type is, by default, Read-only, and that will suffice for this exercise. Should you later wish to allow your users to post to Twitter while logged in through your website, you’ll need to choose Read and Write instead.

Once registered, Twitter will provide you with an OAuth Consumer key and Consumer secret that you’ll need to record for use when developing your login process.

Download the TwitterOAuth PHP Class

Once again, we’ll be making use of the fantastic Twitter/OAuth wrapper class, TwitterOAuth, written by Abraham Williams. As in Part 1, we’ll be using version 0.2.0-beta3; however, this time no modification is required. To start, download a copy of the library.

Set Up Your Login Page

Our first task is to create a page that starts the whole login process on your server. It will need to do a little OAuth work itself, creating a pair of request tokens to attach to our login link.

Create the file login.php containing the following code:

Example 1. login.php

<?php session_start();    // Include class & create require_once("consumer-keys.php");require_once("twitteroauth/twitteroauth.php");    // Create TwitterOAuth object with our Twitter provided keys $tOAuth = new TwitterOAuth($consumerKey, $consumerSecret);    // Generate request tokens$requestToken = $tOAuth->getRequestToken();$_SESSION["oauth_token"] = $requestToken["oauth_token"];$_SESSION["oauth_token_secret"] = $requestToken["oauth_token_secret"];    // Display Twitter log in button with encoded link echo "<a href="". $tOAuth->getAuthorizeURL($requestToken["oauth_token"]) . ""><img src="http://a0.twimg.com/images/dev/buttons/sign-in-with-twitter-d.png"></a>";?>

Now create the file consumer-keys.php with the following code:

Example 2. consumer-keys.php

<?php   // The Twitter provided key & secret for your registered application $consumerKey = "[paste your Twitter provided consumer key]"; $consumerSecret = "[paste your Twitter provided consumer secret]"; ?>

Believe it or not, you’re halfway there already. Go to the login page, and click on the sign-in button to land on Twitter’s website. It will ask you to Allow or Deny “[Your Application Name]” access to your Twitter account.

If you do click on either option at this point, you’ll generate a 404 error. Twitter is trying to load your Callback URL, which we’ve yet to create. Let’s do that now.

Create Your Callback Handler

Next, you’ll create the callback file you specified when you registered your app with Twitter. This file is the controller of the authentication process on your server. Depending on the user’s selection (allow or deny), you now have to perform the appropriate functions.

First, we’ll handle denying a user access. Twitter will display a “denied” page with a link to bounce the user back to your callback URL. It will also attach a GET variable, denied, whose value will be equal to the request token generated on your login page above.

If you wanted to be ultra cautious, you could test for $_GET["denied"] being equal to $_SESSION["oauth_token"], but I haven’t gone that far in the example below. How you handle a denial is entirely up to you. In this case, I’m simply supplying a link back to the login page.

Create the file callback.php containing the following code:

Example 3. callback.php

<?php session_start();    // Include class & create require_once("consumer-keys.php");require_once("twitteroauth/twitteroauth.php");    // User has selected to DENY access if(!empty($_GET["denied"])) {  // could re-direct or display cancelled view/template  // we're just echoing out a message  echo "No deal! <a href='login.php'>Try again?</a>";  die();}?>

Next, we need to handle the more desirable option: allowing your user access to log in to your website. This time the initial request token is sent back in the GET variable oauth_token, which is checked to see that it matches the one stored in our session before proceeding.

At this point, decisions must be made about the storage of these access tokens. You may wish to save them into a cookie (to use in a similar fashion to a “Remember me” checkbox on a normal login system), or in a database to be matched against a local user-associated record. For ease of demonstration, I’m simply placing them into the session’s storage.

After saving the access tokens to the session, you can unregister the previous request tokens as they’re no longer required, and redirect the user:

Example 4. callback.php (continued)

<?php // User has selected to ALLOW access for given token if($_GET["oauth_token"] == $_SESSION["oauth_token"]) {  // Use generated request tokens (from session) to construct object  $tOAuth = new TwitterOAuth($consumerKey, $consumerSecret, $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);  // Retrieve access token from Twitter  $accessToken = $tOAuth->getAccessToken();  // Check we have valid response  if(is_numeric($accessToken["user_id"]))  {    // Save the access tokens to a DB (we're using a session)    $_SESSION["access_token"] = $accessToken;    // Remove request token session variables    unset($_SESSION["oauth_token"]);    unset($_SESSION["oauth_token_secret"]);    // Redirect to main page    header("location: welcome.php");  } else {    header("location: login.php");  }}?>

Congratulations! Your User Has Logged In

Now that Twitter has given us the keys to the kingdom (the access tokens stored in our session), the page that the user is directed to simply needs to check the tokens and verify them with Twitter. After that, your user can proceed as if they had logged in to your site using a custom local login process. As an added bonus, you now have the ability to perform API calls against Twitter.

Create the file welcome.php containing the following code:

Example 5. welcome.php

<?php session_start();      // Include class & createrequire_once("consumer-keys.php");require_once("twitteroauth/twitteroauth.php");      // Check we have active session with access tokens from Twitterif(!empty($_SESSION["access_token"]) && !empty($_SESSION["access_token"]["oauth_token"])) {  // Create new TwitterOAuth object with access tokens  $tOAuth = new TwitterOAuth($consumerKey, $consumerSecret, $_SESSION["access_token"]["oauth_token"], $_SESSION["access_token"]["oauth_token_secret"]);  // Perform an API request  $credentials = $tOAuth->get('account/verify_credentials');  echo "Logged in as @" . $credentials->screen_name;  echo "<br>YAY! You've logged in using Twitter via OAuth!";}?>


Providing a single sign-on function using OAuth and Sign in with Twitter is an effective way of making your site visitors lives a little easier. You also stand to gain some powerful interaction options while protecting your users’ security.

Raj DeutRaj Deut
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week