Skip to content

Commit

Permalink
cache results of verify and decode (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomK authored Oct 15, 2020
1 parent baf5404 commit 9ad75c5
Showing 1 changed file with 45 additions and 6 deletions.
51 changes: 45 additions & 6 deletions src/Fident.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,70 @@ public function getConfig(): FidentConfiguration
return $this->_configuration;
}

protected $_verifyCache = [];

public function verifyJwt(string $rawJwt): bool
{
if(empty($rawJwt))
{
return false;
}

$jwtHash = md5($rawJwt);
if(isset($this->_verifyCache[$jwtHash]))
{
return $this->_verifyCache[$jwtHash];
}

$parts = explode('.', $rawJwt, 3);
if(count($parts) != 3)
{
return false;
$this->_verifyCache[$jwtHash] = false;
return $this->_verifyCache[$jwtHash];
}
[$head64, $payload64, $sig64] = $parts;
$header = json_decode(Strings::urlsafeBase64Decode($head64));
if(!$header || !isset($header->typ) || $header->typ !== 'JWT')
{
return false;
$this->_verifyCache[$jwtHash] = false;
return $this->_verifyCache[$jwtHash];
}
$key = $this->_configuration->getPublicKey();
return openssl_verify("$head64.$payload64", Strings::urlsafeBase64Decode($sig64), $key, OPENSSL_ALGO_SHA256) === 1;
$this->_verifyCache[$jwtHash] = openssl_verify(
"$head64.$payload64",
Strings::urlsafeBase64Decode($sig64),
$key,
OPENSSL_ALGO_SHA256
) === 1;
return $this->_verifyCache[$jwtHash];
}

/**
* @var FidentJwtData[]
*/
protected $_dataCache = [];

public function decodeJwtPayload(string $rawJwt): ?FidentJwtData
{
$data = new FidentJwtData();
if(substr_count($rawJwt, '.') !== 2)
if(empty($rawJwt))
{
return null;
}

$jwtHash = md5($rawJwt);
if(isset($this->_dataCache[$jwtHash]))
{
return $data;
return $this->_dataCache[$jwtHash];
}

if(!$this->verifyJwt($rawJwt))
{
return null;
}

$data = new FidentJwtData();
$this->_dataCache[$jwtHash] = $data;

[, $payload64,] = explode('.', $rawJwt, 3);
$payload = json_decode(Strings::urlsafeBase64Decode($payload64));
$payload->payload = Strings::urlsafeBase64Decode($payload->payload);
Expand Down

0 comments on commit 9ad75c5

Please sign in to comment.