PHP making secure LinkedIn oauth 2.0 login request
In this article, you will learn how to login with a LinkedIn account using LinkedIn oauth client api 2.0 in PHP. Most of the websites have sign-in and sign-up features. The manual registration of the user increases the workload of both users and developers. The developer has to develop a secure registration system for users and users also invest time for registration.
Today, every professional has an account on LinkedIn, which helps them to connect with world professionals. LinkedIn provides an API authentication protocol that allows third party websites to access a user's login. So, instead of providing registration on our web application, why not use LinkedIn oauth service to login in the application? It provides a facility for users to log into the application using LinkedIn account and without providing a new account. LinkedIn provides an API library facility that makes their users give third party developers access to their accounts.
These are the step-by-step process for making a secure LinkedIn oauth login request.
Create App and Get API Key and Secret Key
For developer security purpose, we need to generate a token that identifies both the application and the user. This token works as an ID when anyone tries to login through it. To get this token, go to the LinkedIn developers page -
https://www.linkedin.com/developers/
Next, click on 'Create App', fill all the details. Once you have successfully created, go to the 'auth' tab where we will get the 'Client ID' and 'Client Secret' token. There is a 'Redirect URLs' section where we can set the redirect url. After the user has successfully authorized your applications, the user redirects back to this page. There is also a 'Permissions' section which contains allowed permissions to access the details.
Here, we have created a configuration file and mentioned all the above details.
config.php
<?php
define('API_KEY', 'YOUR_API_KEY');
define('API_SECRET', 'YOUR_SECRET_KEY');
define('REDIRECT_URI', 'http://localhost/oauth/linkedin.php');
define('SCOPE', 'r_basicprofile r_emailaddress');
?>
Make sure to replace all the above with your generated token IDs and redirect URL. Next, we have created a main landing page that we will call in the browser. This file contains a simple login form. On clicking the submit button, this form is submitted to the 'oauth.php' page.
index.php
<html>
<head>
<title>Login with LinkedIn</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<form method='post' action='oauth.php' enctype='multipart/form-data'>
<div class="form-group">
<input type='submit' name='submit' value='Login with LinkedIn' class="btn btn-primary">
</div>
</form>
</body>
</html>
oauth.php
<?php
// Include configuration file
require_once 'config.php';
session_name('linkedin');
session_start();
// Handle error
if(isset($_GET['error'])) {
// The error with description returned by linkedIn
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
}
elseif(isset($_GET['code'])) {
// User authorized your application
if($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
}
else {
if((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if(empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Get Profile Data
$user = response('GET', '/v1/people/~:(id,email-address,firstName,lastName)');
print "Hello".$user->firstName.' '.$user->lastName."\n";
exit;
// Function for authentication
function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?'.http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
// Function to access token
function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?'.http_build_query($params);
// Make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve token information in JSON
$response = file_get_contents($url, false, $context);
$token = json_decode($response);
// Store access token and expiration time in session
$_SESSION['access_token'] = $token->access_token;
$_SESSION['expires_in'] = $token->expires_in;
$_SESSION['expires_at'] = time() + $_SESSION['expires_in'];
return true;
}
// Function to return response
function response($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
$url = 'https://api.linkedin.com' . $resource . '?'.http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,))
);
$response = file_get_contents($url, false, $context);
$user = json_decode($response);
return $user;
}
?>
On successful login, it will ask to access basic profile information as shown below -
Related Articles
Strong Number Program in PHPPHP code to send SMS to mobile from website
Remove duplicates from array PHP
Convert stdclass object to array PHP
PHP sanitize input for MySQL
PHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP