Created
November 26, 2014 16:23
-
-
Save ralphschindler/a585cd74973a97ffee3f to your computer and use it in GitHub Desktop.
A Barebones OAuth2 PHP Client demonstrating the "Password Grant Type"
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 | |
namespace SampleOauth2Client; | |
class Client | |
{ | |
protected $configuration = [ | |
'token_file' => null, // path to a file to store token information | |
'api_authorization_token' => null, // authorization to talk to token service | |
'api_token_url' => null, // url to post to | |
'api_username' => null, // username | |
'api_password' => null, // password | |
'api_scope' => null, // scope to request access for | |
]; | |
public function __construct($configuration) | |
{ | |
$this->configuration = $configuration; | |
} | |
public function getAccessToken($refresh = false) | |
{ | |
if (!isset($this->configuration['token_file'])) { | |
throw new \RuntimeException(__CLASS__ . ' requires a file to store access token information in'); | |
} | |
$tokenDataFile = $this->configuration['token_file']; | |
$tokenData = unserialize(file_get_contents($tokenDataFile)); | |
$tokenIsExpired = (time() > $tokenData['access']['expiration']); | |
if (!$tokenData || $refresh || $tokenIsExpired) { | |
$this->refreshTokens(); | |
} | |
$tokenData = unserialize(file_get_contents($tokenDataFile)); | |
return $tokenData['access']['token']; | |
} | |
protected function refreshTokens() | |
{ | |
$context = stream_context_create([ | |
'http' => [ | |
'method' => 'POST', | |
'header' => "Authorization: Basic {$this->configuration['api_authorization_token']}\r\n" | |
. "Content-Type: application/x-www-form-urlencoded\r\n", | |
'content' => "grant_type=password&username={$this->configuration['api_username']}" | |
. "&password={$this->configuration['api_password']}" | |
. "&scope={$this->configuration['api_scope']}", | |
] | |
]); | |
$content = file_get_contents($this->configuration['api_token_url'], null, $context); | |
if (!strpos($http_response_header[0], '200 OK')) { | |
throw new \RuntimeException('Could not obtain an access token'); | |
} | |
$decoded = json_decode($content, true); | |
$tokenData = [ | |
'access' => [ | |
'token' => $decoded['access_token'], | |
'expiration' => (time() + $decoded['expires_in']) | |
], | |
'refresh' => [ | |
'token' => $decoded['refresh_token'] | |
] | |
]; | |
file_put_contents($this->configuration['token_file'], serialize($tokenData)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Different goals, that's fair enough.
Guzzle, meh! After months away from zf2 development, I forget about the religious sect FIG in php that believes in the one-true-interface ;)