From 75f8017d5644a8a9a2f935ad39119da2690dbe7e Mon Sep 17 00:00:00 2001 From: Clinton Graham Date: Fri, 17 Jul 2020 14:15:39 -0400 Subject: [PATCH] scriptotek/php-primo-search#2: add method to fetch the public key to verify JWT signatures --- spec/PrimoSpec.php | 21 +++++++++++++++++++++ src/Primo.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/spec/PrimoSpec.php b/spec/PrimoSpec.php index d58ab04..4adad87 100644 --- a/spec/PrimoSpec.php +++ b/spec/PrimoSpec.php @@ -110,4 +110,25 @@ function it_accepts_jwt_tokens() $this->setJwtToken('test456'); $this->getJwtToken()->shouldBe('test456'); } + + function it_can_get_public_key() + { + $this->initWithResponses([ + new Response(200, [], 'myPublicKey'), + ]); + + $this->getPublicKey()->shouldBe('myPublicKey'); + } + + function it_can_be_configured_with_public_key() + { + $this->beConstructedWith([ + 'apiKey' => 'magic key!', + 'region' => 'eu', + 'vid' => 'UIO', + 'scope' => 'default_scope', + 'publicKey' => 'ourPublicKey' + ]); + $this->getPublicKey()->shouldBe('ourPublicKey'); + } } diff --git a/src/Primo.php b/src/Primo.php index 0bd5c9a..cb3fcfd 100644 --- a/src/Primo.php +++ b/src/Primo.php @@ -20,6 +20,7 @@ class Primo // For hosted setup protected $apiKey; protected $region; + protected $publicKey; // For on-premises setup protected $baseUrl; @@ -42,6 +43,10 @@ public function __construct( $this->vid = $config['vid']; $this->scope = $config['scope']; + if (isset($config['publicKey'])) { + $this->publicKey = $config['publicKey']; + } + if (isset($config['apiKey'])) { // Hosted $this->apiKey = $config['apiKey']; @@ -87,6 +92,38 @@ public function setScope(string $scope) return $this; } + /** + * Get the JWT public key, preferred cached. + * + * @param $cached bool + * @return string + */ + public function getPublicKey(bool $cached = true) + { + if (!$cached || !isset($this->publicKey)) { + $this->cachePublicKey(); + } + + return $this->publicKey; + } + + /** + * Cache the JWT public key, fetched via the API + */ + protected function cachePublicKey() + { + $pubKey = ''; + $res = $this->request("{$this->baseUrl}/instPublicKey"); + $pubKey = trim($res, '"'); + // This string may be returned with a 200 + if ($pubKey === 'The institution doesn\'t exist or the public key wasn\'t created') { + $pubKey = ''; + } + + $this->publicKey = $pubKey; + } + + protected function getGuestJwtToken() { $res = $this->request("{$this->baseUrl}/guestJwt/{$this->inst}?" . http_build_query([