Skip to content

Commit

Permalink
refactor: add metadata cache (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
gao-sun authored Apr 27, 2024
1 parent 7780a7d commit 4ed7fad
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion samples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
)
);

switch ($_SERVER['PATH_INFO']) {
switch (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)) {
case '/':
case null:
if (!$client->isAuthenticated()) {
Expand Down
2 changes: 1 addition & 1 deletion src/LogtoClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class LogtoClient

function __construct(public LogtoConfig $config, public Storage $storage = new SessionStorage())
{
$this->oidcCore = OidcCore::create($config->endpoint);
$this->oidcCore = OidcCore::create(rtrim($config->endpoint, "/"));
}

/**
Expand Down
18 changes: 15 additions & 3 deletions src/Oidc/OidcCore.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Logto\Sdk\Models\OidcProviderMetadata;
use Phpfastcache\CacheManager;
use Firebase\JWT\JWT;
use Phpfastcache\Helper\Psr16Adapter;

/**
* The core OIDC functions for the Logto client. Provider-agonistic functions
Expand All @@ -23,18 +24,29 @@ class OidcCore

/**
* Create a OidcCore instance for the given Logto endpoint using the discovery URL.
* Note it may take a few time to fetch the provider metadata since it will send a
* network request.
*
* Note it may take a while to fetch the metadata from the endpoint for the first time.
* After that, the metadata will be cached for 1 hour.
*/
static function create(string $logtoEndpoint): OidcCore
{
$defaultDriver = 'Files';
$Psr16Adapter = new Psr16Adapter($defaultDriver);
$client = new Client();
$cacheKey = 'logto_oidc_metadata.' . urlencode($logtoEndpoint);

if ($metadata = $Psr16Adapter->get($cacheKey)) {
return new OidcCore(new OidcProviderMetadata(...$metadata));
}

$body = $client->get(
$logtoEndpoint . '/oidc/.well-known/openid-configuration',
['headers' => ['user-agent' => '@logto/php', 'accept' => '*/*']]
)->getBody()->getContents();
$metadata = json_decode($body, true);
$Psr16Adapter->set($cacheKey, $metadata, 3600);

return new OidcCore(new OidcProviderMetadata(...json_decode($body, true)));
return new OidcCore(new OidcProviderMetadata(...$metadata));
}

/** Generate a random string (32 bytes) for the state parameter. */
Expand Down

0 comments on commit 4ed7fad

Please sign in to comment.