Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b127c3cba8 | |||
| 3039ddc2ec | |||
| 6d9ea6584d | |||
| fde083f36f |
17
CloudObjects/SDK/CustomCacheAndLogInterface.php
Normal file
17
CloudObjects/SDK/CustomCacheAndLogInterface.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
namespace CloudObjects\SDK;
|
||||
|
||||
interface CustomCacheAndLogInterface {
|
||||
|
||||
public function logInfoWithTime($message, $ts);
|
||||
|
||||
public function getFromCacheCustom($id);
|
||||
|
||||
public function putIntoCacheCustom($id, $data, $ttl);
|
||||
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use CloudObjects\SDK\AccountGateway\AccountContext;
|
||||
/**
|
||||
* The ObjectRetriever provides access to objects on CloudObjects.
|
||||
*/
|
||||
class ObjectRetriever {
|
||||
class ObjectRetriever implements CustomCacheAndLogInterface {
|
||||
|
||||
use LoggerAwareTrait;
|
||||
|
||||
@@ -107,19 +107,31 @@ class ObjectRetriever {
|
||||
$this->client = new Client($options);
|
||||
}
|
||||
|
||||
private function logInfoWithTime($message, $ts) {
|
||||
public function logInfoWithTime($message, $ts) {
|
||||
if (isset($this->logger))
|
||||
$this->logger->info($message, [ 'elapsed_ms' => round((microtime(true) - $ts) * 1000) ]);
|
||||
}
|
||||
|
||||
private function getCacheKey($id) {
|
||||
return $this->options['cache_prefix'].$this->options['auth_ns'].'/'.$id;
|
||||
}
|
||||
|
||||
private function getFromCache($id) {
|
||||
return (isset($this->cache) && $this->cache->contains($this->options['cache_prefix'].$id))
|
||||
? $this->cache->fetch($this->options['cache_prefix'].$id) : null;
|
||||
return (isset($this->cache) && $this->cache->contains($this->getCacheKey($id)))
|
||||
? $this->cache->fetch($this->getCacheKey($id)) : null;
|
||||
}
|
||||
|
||||
private function putIntoCache($id, $data, $ttl) {
|
||||
if (isset($this->cache))
|
||||
$this->cache->save($this->options['cache_prefix'].$id, $data, $ttl);
|
||||
$this->cache->save($this->getCacheKey($id), $data, $ttl);
|
||||
}
|
||||
|
||||
public function getFromCacheCustom($id) {
|
||||
return $this->getFromCache('custom/'.$id);
|
||||
}
|
||||
|
||||
public function putIntoCacheCustom($id, $data, $ttl) {
|
||||
$this->putIntoCache('custom/'.$id, $data, $ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -154,16 +154,19 @@ class APIClientFactory {
|
||||
'timeout' => self::DEFAULT_TIMEOUT
|
||||
];
|
||||
|
||||
if ($this->reader->hasProperty($api, 'wa:hasAuthorizationServer')) {
|
||||
if ($this->reader->hasProperty($api, 'oauth2:hasAuthorizationServer')) {
|
||||
// We have an authorization server for this endpoint/API
|
||||
$authServerCoid = $this->reader->getFirstValueIRI($api, 'wa:hasAuthorizationServer');
|
||||
$authServerCoid = $this->reader->getFirstValueIRI($api, 'oauth2:hasAuthorizationServer');
|
||||
$authServerObject = $this->objectRetriever->getObject($authServerCoid);
|
||||
if (!isset($authServer))
|
||||
if (!isset($authServerObject))
|
||||
throw new InvalidObjectConfigurationException("Authorization server object <"
|
||||
. (string)$authServerCoid . "> not available.");
|
||||
|
||||
try {
|
||||
$authServer = new OAuth2AuthServer($authServerObject);
|
||||
$authServer = new OAuth2AuthServer($authServerObject, $this->objectRetriever);
|
||||
} catch (InvalidObjectConfigurationException $e) {
|
||||
throw new InvalidObjectConfigurationException("Authorization server object <"
|
||||
. (string)$authServerCoid . "> could not be loaded; error: " . $e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
throw new InvalidObjectConfigurationException("Authorization server object <"
|
||||
. (string)$authServerCoid . "> could not be loaded. Its definition may be invalid.");
|
||||
|
||||
@@ -9,26 +9,31 @@ namespace CloudObjects\SDK\WebAPI;
|
||||
use Exception;
|
||||
use ML\JsonLD\Node;
|
||||
use GuzzleHttp\Client;
|
||||
use Webmozart\Assert\Assert;
|
||||
use CloudObjects\SDK\NodeReader;
|
||||
use Webmozart\Assert\Assert,
|
||||
Webmozart\Assert\InvalidArgumentException;
|
||||
use CloudObjects\SDK\NodeReader,
|
||||
CloudObjects\SDK\CustomCacheAndLogInterface;
|
||||
use CloudObjects\SDK\Exceptions\InvalidObjectConfigurationException;
|
||||
|
||||
class OAuth2AuthServer {
|
||||
|
||||
private $reader;
|
||||
private $authServer;
|
||||
private $consumer;
|
||||
private $cacheAndLog;
|
||||
|
||||
private $grantType;
|
||||
private $clientId;
|
||||
private $clientSecret;
|
||||
|
||||
public function __construct(Node $authServer) {
|
||||
public function __construct(Node $authServer, CustomCacheAndLogInterface $cacheAndLog) {
|
||||
$this->reader = new NodeReader([
|
||||
'prefixes' => [
|
||||
'oauth2' => 'coid://oauth2.co-n.net/'
|
||||
]
|
||||
]);
|
||||
|
||||
try {
|
||||
Assert::true($this->reader->hasProperty($authServer, 'oauth2:hasTokenEndpoint'),
|
||||
"Authorization Server must have a token endpoint.");
|
||||
Assert::startsWith($this->reader->getFirstValueString($authServer, 'oauth2:hasTokenEndpoint'),
|
||||
@@ -36,20 +41,24 @@ class OAuth2AuthServer {
|
||||
"Token endpoint must be an https:// URL.");
|
||||
Assert::true($this->reader->hasProperty($authServer, 'oauth2:supportsGrantType'),
|
||||
"Authorization Server must support at least one grant type.");
|
||||
Assert::true($this->reader->hasProperty($this->authServer, 'oauth2:usesClientIDFrom'),
|
||||
Assert::true($this->reader->hasProperty($authServer, 'oauth2:usesClientIDFrom'),
|
||||
"Authorization Server must define client ID property.");
|
||||
Assert::true($this->reader->hasProperty($this->authServer, 'oauth2:usesClientSecretFrom'),
|
||||
Assert::true($this->reader->hasProperty($authServer, 'oauth2:usesClientSecretFrom'),
|
||||
"Authorization Server must define client secret property.");
|
||||
|
||||
$this->authServer = $authServer;
|
||||
} catch (InvalidArgumentException $e) {
|
||||
throw new InvalidObjectConfigurationException($e->getMessage());
|
||||
}
|
||||
|
||||
private function assertClientCredentialPropertiesExist() : void {
|
||||
|
||||
$this->authServer = $authServer;
|
||||
$this->cacheAndLog = $cacheAndLog;
|
||||
}
|
||||
|
||||
public function configureConsumer(Node $consumer) : void {
|
||||
$this->assertClientCredentialPropertiesExist();
|
||||
try {
|
||||
Assert::notNull($this->authServer, "Object wasn't initialized correctly.");
|
||||
Assert::notNull($this->cacheAndLog, "Object wasn't initialized correctly.");
|
||||
|
||||
$clientIDProperty = $this->reader->getFirstValueString($this->authServer,
|
||||
'oauth2:usesClientIDFrom');
|
||||
$clientSecretProperty = $this->reader->getFirstValueString($this->authServer,
|
||||
@@ -60,12 +69,17 @@ class OAuth2AuthServer {
|
||||
Assert::true($this->reader->hasProperty($consumer, $clientSecretProperty),
|
||||
"Namespace must have Client Secret");
|
||||
|
||||
} catch (InvalidArgumentException $e) {
|
||||
throw new InvalidObjectConfigurationException($e->getMessage());
|
||||
}
|
||||
|
||||
if ($this->reader->hasPropertyValue($this->authServer,
|
||||
'oauth2:supportsGrantType', 'oauth2:ClientCredentials')) {
|
||||
'oauth2:supportsGrantType', 'oauth2:ClientCredentials'))
|
||||
{
|
||||
// No additional conditions for "client_credentials" flow
|
||||
$this->grantType = 'client_credentials';
|
||||
} else {
|
||||
throw new Exception("No flow/grant_type found.");
|
||||
throw new InvalidObjectConfigurationException("No flow/grant_type found.");
|
||||
}
|
||||
|
||||
$this->consumer = $consumer;
|
||||
@@ -74,11 +88,19 @@ class OAuth2AuthServer {
|
||||
}
|
||||
|
||||
public function getAccessToken() {
|
||||
try {
|
||||
Assert::notNull($this->authServer, "Object wasn't initialized correctly.");
|
||||
Assert::notNull($this->cacheAndLog, "Object wasn't initialized correctly.");
|
||||
|
||||
Assert::notNull($this->consumer, "Missing consumer.");
|
||||
Assert::notNull($this->grantType, "Missing grant_type.");
|
||||
Assert::notNull($this->clientId, "Missing client_id.");
|
||||
Assert::notNull($this->clientSecret, "Missing client_secret.");
|
||||
|
||||
} catch (InvalidArgumentException $e) {
|
||||
throw new InvalidObjectConfigurationException($e->getMessage());
|
||||
}
|
||||
|
||||
$client = new Client;
|
||||
$tokenEndpointUrl = $this->reader->getFirstValueString($this->authServer, 'oauth2:hasTokenEndpoint');
|
||||
$params = [
|
||||
@@ -90,16 +112,32 @@ class OAuth2AuthServer {
|
||||
switch ($this->grantType) {
|
||||
case "client_credentials":
|
||||
// no additional params needed
|
||||
break;
|
||||
default:
|
||||
throw new Exception("No flow/grant_type found.");
|
||||
}
|
||||
|
||||
$grantCacheKey = sha1(json_encode($params));
|
||||
|
||||
$ts = microtime(true);
|
||||
$tokenResponse = json_decode($this->cacheAndLog->getFromCacheCustom($grantCacheKey), true);
|
||||
|
||||
if (isset($tokenResponse)) {
|
||||
$this->cacheAndLog->logInfoWithTime("Reused access token for <".$this->authServer->getId()."> from cache.", $ts);
|
||||
} else {
|
||||
// Nothing cached, fetch from server
|
||||
$tokenResponse = json_decode($client->post($tokenEndpointUrl, [
|
||||
'form_params' => $params
|
||||
])->getBody(true));
|
||||
])->getBody(true), true);
|
||||
|
||||
Assert::keyExists($tokenResponse, 'access_token');
|
||||
|
||||
$expiry = isset($tokenResponse['expires_in']) ? $tokenResponse['expires_in'] : 84600;
|
||||
|
||||
$this->cacheAndLog->logInfoWithTime("Retrieved access token for <".$this->authServer->getId()."> from token endpoint and will cache for ".$expiry." seconds.", $ts);
|
||||
$this->cacheAndLog->putIntoCacheCustom($grantCacheKey, json_encode($tokenResponse), $expiry);
|
||||
}
|
||||
|
||||
return $tokenResponse['access_token'];
|
||||
}
|
||||
}
|
||||
736
composer.lock
generated
736
composer.lock
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user