Created
October 7, 2019 16:52
-
-
Save librarywebchic/67a32f78c0955efa775eeff60d79114f to your computer and use it in GitHub Desktop.
Obtain an Access Token with an Authorization code
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
use GuzzleHttp\Client; | |
use GuzzleHttp\Exception\RequestException; | |
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider; | |
use League\OAuth2\Client\Provider\GenericProvider; | |
$setup_options = [ | |
'clientId' => WSKEY, | |
'clientSecret' => SECRET, | |
'redirectUri' => 'http://localhost:8080/' | |
'urlAuthorize' => 'https://oauth.oclc.org/auth', | |
'urlAccessToken' => 'https://oauth.oclc.org/token', | |
'urlResourceOwnerDetails' => '', | |
'scopes' => ['WorldCatMetadataAPI', 'refresh_token'] | |
]; | |
$basicAuth_provider = new HttpBasicAuthOptionProvider(); | |
$provider = new GenericProvider($setup_options, ['optionProvider' => $basicAuth_provider]); | |
// If we don't have an authorization code then get one | |
if (!isset($_GET['code'])) { | |
// Fetch the authorization URL from the provider; this returns the | |
// urlAuthorize option and generates and applies any necessary parameters | |
// (e.g. state). | |
$authorizationUrl = $provider->getAuthorizationUrl(); | |
// Get the state generated for you and store it to the session. | |
$_SESSION['oauth2state'] = $provider->getState(); | |
// Redirect the user to the authorization URL. | |
header('Location: ' . $authorizationUrl); | |
exit; | |
// Check given state against previously stored one to mitigate CSRF attack | |
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { | |
if (isset($_SESSION['oauth2state'])) { | |
unset($_SESSION['oauth2state']); | |
} | |
exit('Invalid state'); | |
} else { | |
try { | |
// Try to get an access token using the authorization code grant. | |
$accessToken = $provider->getAccessToken('authorization_code', [ | |
'code' => $_GET['code'] | |
]); | |
$url = SERVICE_URL . "/bib/data/1"; | |
$client = new Client(); | |
$headers = array(); | |
$headers['Authorization'] = "Bearer " . $accessToken->getToken(); | |
try { | |
$response = $client->request('GET', $url, ['headers' => $headers]); | |
$xml = $response->getBody(); | |
} catch (RequestException $error) { | |
print_r($error); | |
} | |
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { | |
// Failed to get the access token or user details. | |
exit($e->getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment