Skip to content

Commit 4ed7fad

Browse files
authored
refactor: add metadata cache (#12)
1 parent 7780a7d commit 4ed7fad

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

samples/index.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
)
2727
);
2828

29-
switch ($_SERVER['PATH_INFO']) {
29+
switch (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)) {
3030
case '/':
3131
case null:
3232
if (!$client->isAuthenticated()) {

src/LogtoClient.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class LogtoClient
6464

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

7070
/**

src/Oidc/OidcCore.php

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Logto\Sdk\Models\OidcProviderMetadata;
1111
use Phpfastcache\CacheManager;
1212
use Firebase\JWT\JWT;
13+
use Phpfastcache\Helper\Psr16Adapter;
1314

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

2425
/**
2526
* Create a OidcCore instance for the given Logto endpoint using the discovery URL.
26-
* Note it may take a few time to fetch the provider metadata since it will send a
27-
* network request.
27+
*
28+
* Note it may take a while to fetch the metadata from the endpoint for the first time.
29+
* After that, the metadata will be cached for 1 hour.
2830
*/
2931
static function create(string $logtoEndpoint): OidcCore
3032
{
33+
$defaultDriver = 'Files';
34+
$Psr16Adapter = new Psr16Adapter($defaultDriver);
3135
$client = new Client();
36+
$cacheKey = 'logto_oidc_metadata.' . urlencode($logtoEndpoint);
37+
38+
if ($metadata = $Psr16Adapter->get($cacheKey)) {
39+
return new OidcCore(new OidcProviderMetadata(...$metadata));
40+
}
41+
3242
$body = $client->get(
3343
$logtoEndpoint . '/oidc/.well-known/openid-configuration',
3444
['headers' => ['user-agent' => '@logto/php', 'accept' => '*/*']]
3545
)->getBody()->getContents();
46+
$metadata = json_decode($body, true);
47+
$Psr16Adapter->set($cacheKey, $metadata, 3600);
3648

37-
return new OidcCore(new OidcProviderMetadata(...json_decode($body, true)));
49+
return new OidcCore(new OidcProviderMetadata(...$metadata));
3850
}
3951

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

0 commit comments

Comments
 (0)