Created
July 9, 2014 14:30
-
-
Save AParks/113ce501ee18e6f590f4 to your computer and use it in GitHub Desktop.
A sample server-side script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'curl' . DIRECTORY_SEPARATOR . 'curl.php'; | |
$Curl = new Curl(); | |
// This is called once, after we get a code back | |
if (!empty($_GET['code'])) { | |
// Make sure there wasn't an error authenticating | |
if (!empty($_GET['error'])) { | |
die('Error: ' . $_GET['error']); | |
} | |
// CSRF check | |
if ($_GET['state'] !== 'something') { | |
die('Naughty, naughty'); | |
} | |
// Exchange code for token | |
$url = '/oauth2/v1/grant'; | |
$result = $Curl->post($url, array( | |
'code' => $_GET['code'], | |
'grant_type' => 'authorization_code', | |
'client_id' => 'demo-server-flow-key', | |
'client_secret' => 'secret', | |
'redirect_uri' => 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] | |
)); | |
$body = $result->body; | |
$data = json_decode($body, true); | |
if (empty($data)) { | |
die('Error retrieving token data'); | |
} | |
$access_token = $data['access_token']; | |
echo 'Token data from auth endpoint ' . $url . ':<br />'; | |
echo '<pre>' . print_r($data, true) . '</pre>'; | |
echo '<br /><br />'; | |
// Verify token | |
$url = '/oauth2/v1/token'; | |
$result = $Curl->get($url, array( | |
'access_token' => $access_token | |
)); | |
$body = $result->body; | |
$data = json_decode($body, true); | |
if (empty($data)) { | |
die('Error verifying token'); | |
} | |
if ($data['client_id'] !== 'demo-server-flow-key') { | |
die('Naughty, naughty'); | |
} | |
echo 'Token verification from auth endpoint ' . $url . ':<br />'; | |
echo '<pre>' . print_r($data, true) . '</pre>'; | |
// Access a resource which gives back data about the authorized User ID | |
$url = '/v1/users/me'; | |
$result = $Curl->get($url, array( | |
'access_token' => $access_token | |
)); | |
$body = $result->body; | |
$data = json_decode($body, true); | |
if (empty($data)) { | |
die('Error accessing resource'); | |
} | |
echo 'User data from API resource ' . $url . ':<br />'; | |
echo '<pre>' . print_r($data, true) . '</pre>'; | |
die(); | |
echo '<a href="/oauth2/v1/authorize?client_id=demo-server-flow-key&response_type=code&state=something">Log in</a>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment