Sei sulla pagina 1di 7

How to Authenticate Users With Twitter OAuth

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, Ill show you how to use Twitter as your one-click authentication system, just as we did with Facebook.

Step 1: Setting Up The Application


Well first need to set up a new Twitter application. Register a new app at dev.twitter.com/apps/ 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.com/twitter_login.php(http://localhost/ wont be accepted

because it doesnt have a domain name). Finally, select Read & Write. Fill in the captcha, click Register Application, and accept the Terms of Service. Now, youll see the screen as shown below.

We will be using the Consumer key and Consumer secret values shortly. Now that this is done, lets download a library. As we will be coding with PHP, it seems the best one istwitteroauth; but if youre using another language, youll find other good libraries here.

Find the twitteroauth directory inside the zip file, and extract it to your applications folder. Finally, since were using Twitter to authenticate users, well need a database table to store those users. Heres a quick example of what we will be doing.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9.

CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(10), `oauth_uid` text, `oauth_token` text, `oauth_secret` text, `username` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Notice the oauth_token and oauth_secret fields. Twitters OAuth requires token and a token_secretvalues to authenticate the users, so thats why were 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. Lets begin by including the library and starting a session handler.
view plaincopy to clipboardprint?

1. 2.

require("twitteroauth/twitteroauth.php"); session_start();

After that, lets create a new TwitterOAuth instance, giving it the consumer key and consumer secret that Twitter gave us when we created the application. Then, well request the authentication tokens, saving them to the session, and redirect the user to Twitter for authorization.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.

// The TwitterOAuth instance $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET'); // Requesting authentication tokens, the parameter is the URL we will be redirected to $request_token = $twitteroauth->getRequestToken('http://localhost.com/twitter_oauth.php'); // Saving them into the session $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; // If everything goes well.. if($twitteroauth->http_code==200){ // Let's generate the URL and redirect $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']); header('Location: '. $url); } else { // It's a bad idea to kill the script, but we've got to know when there's an error. die('Something wrong happened.'); }

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

Click allow, and you will be redirected to http://localhost.com/twitter_oauth.php since we set this URL as a parameter in the getRequestToken statement. We havent 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.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6.

if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){ // We've got everything we need } else { // Something's missing, go back to square 1 header('Location: twitter_login.php'); }

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, well do a quick test to see if everything works out.
view plaincopy to clipboardprint?

1. 2.

// TwitterOAuth instance, with two new parameters we got in twitter_login.php $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESS ION['oauth_token_secret']); 3. // Let's request the access token 4. $access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']); 5. // Save it in a session var 6. $_SESSION['access_token'] = $access_token; 7. // Let's get the user's info 8. $user_info = $twitteroauth->get('account/verify_credentials'); 9. // Print user's info 10. print_r($user_info);

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

It is very important to realize that the oauth_verifier hasnt been used before this. If you see the users 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 users info we can go ahead and register them, but first we have to check if they exist in our database. Lets begin by connecting to the database. Add these lines in the scripts beginning.
view plaincopy to clipboardprint?

1. 2.

mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD'); mysql_select_db('YOUR_DATABASE');

Modify the database info as required. Now, just below where we fetch the users info, well have to check for the user in our database. If he or she is not there, well 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 users info to the session vars and redirect to twitter_update.php.
view plaincopy to clipboardprint?

1. if(isset($user_info->error)){ 2. // Something's wrong, go back to square 1 3. header('Location: twitter_login.php'); 4. } else { 5. // Let's find the user by its ID 6. $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id); 7. $result = mysql_fetch_array($query); 8. 9. // If not, let's add it to the database 10. if(empty($result)){ 11. $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')"); 12. $query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id()); 13. $result = mysql_fetch_array($query); 14. } else { 15. // Update the tokens 16. $query = mysql_query("UPDATE users SET oauth_token = '{$access_token['oauth_token']}', oauth_secret = '{$access_token['oauth _token_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}"); 17. } 18. 19. $_SESSION['id'] = $result['id']; 20. $_SESSION['username'] = $result['username']; 21. $_SESSION['oauth_uid'] = $result['oauth_uid']; 22. $_SESSION['oauth_provider'] = $result['oauth_provider']; 23. $_SESSION['oauth_token'] = $result['oauth_token']; 24. $_SESSION['oauth_secret'] = $result['oauth_secret']; 25. 26. header('Location: twitter_update.php'); 27. }

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.
view plaincopy to clipboardprint?

1. 2. 3. 4.

if(!empty($_SESSION['username'])){ // User is logged in, redirect header('Location: twitter_update.php'); }

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


view plaincopy to clipboardprint?

1.

<h2>Hello <?=(!empty($_SESSION['username']) ? '@' . $_SESSION['username'] : 'Guest'); ?></h2>

Lets 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. Well get to the basics, as most of these features are accessed in a similar way. Just like the other two scripts, well need to create the TwitterOAuth instance, including the variables in the session.
view plaincopy to clipboardprint?

1. 2. 3.

if(!empty($_SESSION['username'])){ $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SE SSION['oauth_secret']); }

Well begin with the users timeline. The reference tells us that the path is statuses/home_timeline; ignore the version and format, the library will take care of it.
view plaincopy to clipboardprint?

1. 2.

$home_timeline = $twitteroauth->get('statuses/home_timeline'); print_r($home_timeline);

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, gets second parameter is an array of every option needed, so if you want to fetch the latest forty tweets, heres the code:
view plaincopy to clipboardprint?

1.

$home_timeline = $twitteroauth->get('statuses/home_timeline', array('count' => 40));

Also, you can see somebody elses timeline, as long as its not protected. statuses/user_timelinerequires either a users id or screen name. If you want to check @nettuts timeline, youll have to use the following snippet:
view plaincopy to clipboardprint?

1.

$nettuts_timeline = $twitteroauth->get('statuses/user_timeline', array('screen_name' => 'nettuts'));

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/createrequires just one, either screen_name or user_id.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5.

$follows_faelazo = $twitteroauth->get('friendships/exists', array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo')); if(!$follows_faelazo){ echo 'You are NOT following @faelazo!'; $twitteroauth->post('friendships/create', array('screen_name' => 'faelazo')); }

You can unfollow an user with basically the same code that creates a follow, just replace create withdestroy:
view plaincopy to clipboardprint?

1. 2. 3. 4.

$follows_faelazo = $twitteroauth->get('friendships/exists', array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo')); if($follows_faelazo){ echo 'You are following @faelazo! Proceed to unfollow...'; $twitteroauth->post('friendships/destroy', array('screen_name' => 'faelazo'));

5.

Step 5: Posting Updates


This is probably the most interesting section, since its Twitters 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.
view plaincopy to clipboardprint?

1.

$twitteroauth->post('statuses/update', array('status' => 'Hello Nettuts+'));

Now go to your Twitter profile page and youll see your tweet.

Lets 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 doesnt require additional parameters.
view plaincopy to clipboardprint?

1.

$twitteroauth->post('statuses/retweet/19706871538');

To delete a tweet, youll have to pass the status id youll be destroying in the first parameter, just like retweeting. If the tweets id is 123456789, the code to destroy will be.
view plaincopy to clipboardprint?

1.

$twitteroauth->post('statuses/destroy/123456789');

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

Conclusions
Twitters API is quite easy to understand; its far more documented than even Facebooks (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, youll 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 youve 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?

Potrebbero piacerti anche