Search code examples
phpoauth-2.0linkedin-api

PHP - Authorizate on LinkedIN API


I try to make some simple LinkedIN api call, starting with authorization. For test purpose I create just this $url which I know it works and go to open it.

But there is one difference, if I call this URL via code below and enter my linkedin credentials I am automaticly redirect to

http://localhost/uas/oauth2/authorizedialog/submit

which looks like some linkedin URL replaced with"localhost" instead and I am sure its not my redirect_uri and I do not defined it anywhere.

I cant find the reason why this is happening, If I open page directly in browser (just copy paste URL from $url) after login I am redirect to example.com as it should be.

My code:

//define path

$url = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=MyIdHere&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Flinkedin&state=DCEeFWf45A53sdfKef424&scope=r_basicprofile";

// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/x-www-form-urlencoded'          
));       

 // execute the request
 $output = curl_exec($ch);

 // output the auth information - includes the header
 var_dump($output);

// close curl resource to free up system resources
curl_close($ch);
?>

Thanks for any advise.


Solution

  • Your cURL code does not follow redirects as a browser does, so there's no followup to the Location header in the response presented by LinkedIn. See also Make curl follow redirects?.

    But: you also should not actually try and fix that since the OAuth 2.0 flow is meant to interact with the user via a browser and reverse engineering it in PHP will break at some point. Instead you should obtain an access token via the regular browser-based flow, and use that in your PHP code to get access to LinkedIn APIs.