Logging in using Facebook credentials with laravel

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

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://developers.facebook.com.
2. Get the App ID and App Secret keys, and in the app/config directory, create a file
named as fb_auth.php:
return array(
“base_url” => “http://path/to/our/app/fbauth/auth”,
“providers” => array (
“Facebook” => array (
“enabled” => TRUE,
“keys” => array (“id” => “APP_ID”, “secret” =>
“scope” => “email”

3. Create a route in routes.php to hold our Facebook login button:
Route::get(‘facebook’, function()
return “<a href=’fbauth’>Login with Facebook</a>”;
4. Make a route to process the login information and display it:
Route::get(‘fbauth/{auth?}’, function($auth = NULL)
if ($auth == ‘auth’) {
try {

} catch (Exception $e) {
return Redirect::to(‘fbauth’);
try {
$oauth = new Hybrid_Auth(app_path()
. ‘/config/fb_auth.php’);
$provider = $oauth->authenticate(‘Facebook’);
$profile = $provider->getUserProfile();
catch(Exception $e) {
return $e->getMessage();
echo ‘Welcome ‘ . $profile->firstName . ‘ ‘
. $profile->lastName . ‘<br>’;
echo ‘Your email: ‘ . $profile->email . ‘<br>’;

how its work…

After getting our Facebook API credentials, we need to create a configuration file with those
credentials and our callback URL. We also need to pass in the scope, which is any extra
permission we might want from our user. In this case, we’re just going to get their e-mail ID.
Our facebook login page is a simple link to a route where we do the authentication. The user
will then be taken to Facebook to login and/or authorize our site, and then redirected back to
our fbauth route.
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 *