Skip to content

Commit

Permalink
scriptotek#2: add method to fetch the public key to verify JWT signat…
Browse files Browse the repository at this point in the history
…ures
  • Loading branch information
ctgraham committed Jul 17, 2020
1 parent 8753000 commit 75f8017
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
21 changes: 21 additions & 0 deletions spec/PrimoSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
37 changes: 37 additions & 0 deletions src/Primo.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class Primo
// For hosted setup
protected $apiKey;
protected $region;
protected $publicKey;

// For on-premises setup
protected $baseUrl;
Expand All @@ -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'];
Expand Down Expand Up @@ -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([
Expand Down

0 comments on commit 75f8017

Please sign in to comment.