1. Code
  2. PHP

How to Authenticate Users With Twitter OAuth

Scroll to top
Read Time: 9 min

Beginning August 16th, Twitter will no longer support the basic authentication protocol for its platform. That means the only way to authenticate users will be through a Twitter application. In this tutorial, I'll show you how to use Twitter as your one-click authentication system, just as we did with Facebook.

Step 1: Setting Up The Application

We'll first need to set up a new Twitter application.

  • Register a new app at
  • Fill in the fields for your site accordingly, just be sure to select Browser in Application Type, and set the Callback URL to something like (http://localhost/ won't be accepted because it doesn't have a domain name).
  • Finally, select Read & Write. Fill in the captcha, click "Register Application," and accept the Terms of Service.

Now, you'll see the screen as shown below.

We will be using the Consumer key and Consumer secret values shortly.

Now that this is done, let's download a library. As we will be coding with PHP, it seems the best one is twitteroauth; but if you're using another language, you'll find other good libraries here.

Find the twitteroauth directory inside the zip file, and extract it to your application's folder.

Finally, since we're using Twitter to authenticate users, we'll need a database table to store those users. Here's a quick example of what we will be doing.

Notice the oauth_token and oauth_secret fields. Twitter's OAuth requires token and a token_secret values to authenticate the users, so that's why we're including those. With that, we are done with the setup!

Step 2: Registering Users

In this step we, will be doing three things:

  • Requesting authorization from Twitter.
  • Registering or, if the user is already registered, logging the user in.
  • Setting the data into a session.

Requesting authorization

The OAuth workflow starts by generating a URL for the request; the user is redirected to that URL and is asked for authorization. After granting it, the application redirects back to our server with two tokens in the URL parameters, which are required for the authentication.

Let's begin by including the library and starting a session handler.

After that, let's create a new TwitterOAuth instance, giving it the consumer key and consumer secret that Twitter gave us when we created the application. Then, we'll request the authentication tokens, saving them to the session, and redirect the user to Twitter for authorization.

Save it as twitter_login.php, go to or whatever your local host name is. If everything went correctly, you should be redirected to, and you should see something like this.

Click allow, and you will be redirected to -- since we set this URL as a parameter in the getRequestToken statement. We haven't created that file, so it should throw an error. Create that file, and then include the library and start a session, just like we did in the first file.

After that, we will need three things:

  • Auth verifier in the URL query data
  • Auth token from the session
  • Auth secret from the session

So, the first thing to do in this script is validate this data and redirect if one of these variables is empty.

Now, if everything is set, inside the conditional we will be creating the TwitterOAuth instance, but with the tokens we just got as third and fourth parameters; after that, we will be getting the access token, which is an array. That token is the one we will be saving to the database. Finally, we'll do a quick test to see if everything works out.

If nothing goes wrong, the print_r should show the user's data. You can get the user's id with $user_info->id, his or her username with $user_info->screen_name; there's a bunch of other info in there as well.

It is very important to realize that the oauth_verifier hasn't been used before this. If you see the user's info correctly and then reload the page, the script will throw an error since this variable has been used. Just go back to twitter_login.php and it will automatically generate another fresh token.

Registering users

Now that we have the user's info we can go ahead and register them, but first we have to check if they exist in our database. Let's begin by connecting to the database. Add these lines in the script's beginning.

Modify the database info as required. Now, just below where we fetch the user's info, we'll have to check for the user in our database. If he or she is not there, we'll enter the info. If the user has been registered, we must update the tokens, because Twitter has generated new ones and the ones we have in the database are now unusable. Finally, we set the user's info to the session vars and redirect to twitter_update.php.

Note that these queries are not validated; if you leave them as they are, you are leaving your database vulnerable. Finally, below the database connection, we should set a check to verify that the user is logged in.

You can now greet the user by his or her username.

Let's get to the fun side: updating, following and reading.

Step 3: Reading Statuses

There are over twenty categories of resources available: timeline, tweets, users, trends, lists, direct messages, etc. Each one has a bunch of methods, you can check them all in the official documentation. We'll get to the basics, as most of these features are accessed in a similar way.

Just like the other two scripts, we'll need to create the TwitterOAuth instance, including the variables in the session.

We'll begin with the user's timeline. The reference tells us that the path is statuses/home_timeline; ignore the version and format, the library will take care of it.

That will get you the timeline. You can fetch each item with a foreach loop. However, the reference specifies some optional parameters like count, which limits how many tweets will be fetched. In fact, get's second parameter is an array of every option needed, so if you want to fetch the latest forty tweets, here's the code:

Also, you can see somebody else's timeline, as long as it's not protected. statuses/user_timeline requires either a user's id or screen name. If you want to check @nettuts timeline, you'll have to use the following snippet:

As you can see, after authenticating, reading timelines is a breeze.

Step 4: Friendships

With friendships, you can check if a user follows another one, as well as follow or unfollow other users. This snippet will check if you are following me and and will create the follow if not.

But first, check the friendships/exists and friendships/create reference. Notice something? friendships/create method is POST. Fortunately, the library includes a post() function, which works just as the get() function; the main difference is that get() is for reading and post() is for creating, deleting or updating.

Anyways, friendships/exists requires two parameters: user_a and user_b, and friendships/create requires just one, either screen_name or user_id.

You can unfollow an user with basically the same code that creates a follow, just replace create with destroy:

Step 5: Posting Updates

This is probably the most interesting section, since it's Twitter's core: posting an update, as you might have imagined, is pretty straightforward. The path is statuses/update, the method is POST (since we are not reading), and the one required argument is status.

Now go to your Twitter profile page and you'll see your tweet.

Let's retweet @Nettuts' update announcing the HTML 5 Competition; the status id is 19706871538 and the reference tells us that the path is statuses/retweet/:id, where the :id part is the status id we will be retweeting. The method is POST and it doesn't require additional parameters.

To delete a tweet, you'll have to pass the status id you'll be destroying in the first parameter, just like retweeting. If the tweet's id is 123456789, the code to destroy will be.

Of course, this code can only delete tweets made by the authenticated user.


Twitter's API is quite easy to understand; it's far more documented than even Facebook's (even though Facebook offers an in-house library). Unfortunately, the authentication is not as smooth as we might hope, depending on session data.

One thing worth noticing is that, once a Twitter user has been authorized (assuming the app has read and write permissions), you have plenty of control over this account. If you change something on behalf of the user without his permission, you'll create trouble. Use it with caution!

The API changes coming to Twitter will deny basic authentication; Twitter is focusing on ceasing the countless scams that trick users into giving up their login credentials. OAuth is the solution; and, if you've worked through the Facebook Connect tutorial, you can now provide your website or app users with a quick login without credentials, using your choice of the two most used social networks. How cool is that?

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.