Logging in using Twitter credentials with laravel

If we don’t want to worry about storing the user’s information and credentials, we could use
OAuth to authenticate with another service. A popular service to use for logins is Twitter. With
Laravel and the HybridAuth library, we can easily implement OAuth authentication with Twitter.

Getting ready

For this recipe, we need to have the HybridAuth package installed and set up as in the Setting
up OAuth with the HybridAuth package recipe.

How to do it…

To complete this recipe, follow these steps:
1. Create a new app at https://dev.twitter.com/apps.
2. Get the Consumer Key and the Consumer Secret, and in the app/config directory,
create a file named as tw_auth.php:
<?php
return array(
“base_url” => “http://path/to/our/app/twauth/auth”,
“providers” => array (
“Twitter” => array (
“enabled” => true,
“keys” => array (“key” => “CONSUMER_KEY”,
“secret” => “CONSUMER_SECRET”)
)
)
);

3. Create a route in routes.php for our Twitter login button:
Route::get(‘twitter’, function()
{
return “<a href=’twauth’>Login with Twitter</a>”;
});
4. Make a route to process the Twitter information:
Route::get(‘twauth/{auth?}’, function($auth = NULL)
{
if ($auth == ‘auth’) {
try {
Hybrid_Endpoint::process();
} catch (Exception $e) {

return Redirect::to(‘twauth’);
}
return;
}
try {
$oauth = new Hybrid_Auth(app_path()
. ‘/config/tw_auth.php’);
$provider = $oauth->authenticate(‘Twitter’);
$profile = $provider->getUserProfile();
}
catch(Exception $e) {
return $e->getMessage();
}
echo ‘Welcome ‘ . $profile->displayName . ‘<br>’;
echo ‘Your image: <img src=”‘ . $profile->photoURL
. ‘”>’;
dd($profile);
});

How it works…

After getting our Twitter API credentials, we need to create a configuration file with those
credentials and our callback URL.
We then make a Twitter login view, which is a simple link to a route where we do the
authentication. The user will then be taken to Twitter to login and/or authorize our site, and then
redirected back to our twauth route. Here, we get their display name and their Twitter icon.
At this point, we’re just displaying the information that was returned, but we’d also probably
want to save the information to our own database.

Leave a Reply

Your email address will not be published. Required fields are marked *