Logging in using LinkedIn with laravel

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

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://www.linkedin.com/secure/developer.
2. Get the API Key and the Secret Key, and in the app/config directory, create a file
named li_auth.php:
<?php
return array(
“base_url” => “http://path/to/our/app/liauth/auth”,
“providers” => array (
“LinkedIn” => array (
“enabled” => true,
“keys” => array (“key” => “API_KEY”,
“secret” => “SECRET_KEY”)
)
)
);
3. Create a route in routes.php for our LinkedIn login button:
Route::get(‘linkedin’, function()
{
return “<a href=’liauth’>Login with LinkedIn</a>”;
});

4. Make a route to process the LinkedIn information:
Route::get(‘liauth/{auth?}’, function($auth = NULL)
{
if ($auth == ‘auth’) {
try {
Hybrid_Endpoint::process();
} catch (Exception $e) {
return Redirect::to(‘liauth’);
}
return;
}
try {

$oauth = new Hybrid_Auth(app_path()
. ‘/config/li_auth.php’);
$provider = $oauth->authenticate(‘LinkedIn’);
$profile = $provider->getUserProfile();
}
catch(Exception $e) {
return $e->getMessage();
}
echo ‘Welcome ‘ . $profile->firstName . ‘ ‘ . $profile
->lastName . ‘<br>’;
echo ‘Your email: ‘ . $profile->email . ‘<br>’;
echo ‘Your image: <img src=”‘ . $profile->photoURL
. ‘”>’;
dd($profile);
});

How its work..

After getting our LinkedIn API credentials, we need to create a configuration file with those
credentials and our callback URL.
We then make a LinkedIn login view, with a simple link to a route where we do the LinkedIn
authentication. The user will then be taken to the LinkedIn site to login and/or authorize our
site, and then redirected back to our liauth route. Here, we get their first name, last name,
e-mail ID, and their avatar.
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 *