Skip to content

Commit

Permalink
Merge branch 'keycloak-pub-key'
Browse files Browse the repository at this point in the history
  • Loading branch information
eluhr committed Jul 1, 2024
2 parents 8e2d184 + 822bdfb commit 358823c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ return [
'validationConstraints' => function (JwtTools $jwt) {
return [
new SignedWith($jwt->buildSigner(Jwt::RS256), InMemory::plainText(getenv('KEYCLOAK_PUBLIC_KEY_FILE'))),
// You could also use this line if you do not want to use a separate public key file
// new SignedWith($jwt->buildSigner(Jwt::RS256), InMemory::plainText(KeycloakHelper::publicKeyFromIssuer(getenv('KEYCLOAK_ISSUER_URL')))),
new IssuedBy(getenv('KEYCLOAK_ISSUER_URL')),
new LooseValidAt(SystemClock::fromUTC()),
];
Expand Down
62 changes: 62 additions & 0 deletions src/helpers/KeycloakHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace dmstr\usuario\keycloak\helpers;

use Yii;
use yii\caching\CacheInterface;
use yii\httpclient\Client;

class KeycloakHelper
{

/**
* Returns the public key from the issuer url. E.g.: http://keycloak:8080/realms/your-realm
*/
public static function publicKeyFromIssuer(string $issuerUrl): ?string
{
$cache = Yii::$app->getCache();
// Check if cache component does exist
if ($cache instanceof CacheInterface) {
$publicKey = $cache->getOrSet(__CLASS__ . '.publicKey', function () use ($issuerUrl) {
// Get public key from issuer url. Cache it if it exists. If there is an error or invalid public key. Do not cache
$publicKey = self::fetchPublicKeyFromIssuer($issuerUrl);
if (is_string($publicKey)) {
return $publicKey;
}
return false;
}, 3600);

if (is_string($publicKey)) {
return $publicKey;
}
return null;
}
// If cache component does not exist. Fetch key directly
return self::fetchPublicKeyFromIssuer($issuerUrl);

}

protected static function fetchPublicKeyFromIssuer(string $issuerUrl): ?string
{
$client = new Client([
'baseUrl' => $issuerUrl
]);

$response = $client->get('')->send();

if ($response->getIsOk()) {
$publicKeyContent = $response->getData()['public_key'] ?? null;
} else {
$publicKeyContent = null;
}

if (!empty($publicKeyContent)) {
// Build public key in format needed by lombucci package
$publicKey = '-----BEGIN PUBLIC KEY-----' . PHP_EOL . $publicKeyContent . PHP_EOL . '-----END PUBLIC KEY-----';
} else {
$publicKey = null;
}

return $publicKey;
}
}

0 comments on commit 358823c

Please sign in to comment.