84 lines
2.4 KiB
PHP
84 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\User\Authorize\Bearer;
|
|
|
|
class JsonWebTokenDecoder
|
|
{
|
|
protected array $header;
|
|
|
|
protected array $payload;
|
|
|
|
public function __construct(
|
|
public string $encoded,
|
|
public string $secretKey,
|
|
) {}
|
|
|
|
protected function parse() : bool
|
|
{
|
|
try {
|
|
list($encodedHeader, $encodedPayload, $signature) = explode('.', $this->encoded);
|
|
|
|
foreach([ 'header' => $encodedHeader, 'payload' => $encodedPayload ] as $key => $value) {
|
|
$decoded = static::base64url_decode($value) ;
|
|
|
|
if ( $decoded !== false ){
|
|
$jsonArray = json_decode($decoded, true);
|
|
|
|
if ( is_array($jsonArray) ) {
|
|
if ($key === 'header') {
|
|
JsonWebTokenValidate::validateHeaderType($jsonArray);
|
|
JsonWebTokenValidate::validateHeaderAlgorithm($jsonArray);
|
|
}
|
|
elseif ($key === 'payload') {
|
|
JsonWebTokenValidate::validatePayloadExpiration($jsonArray);
|
|
}
|
|
|
|
$this->$key = $jsonArray;
|
|
}
|
|
else {
|
|
throw new JsonWebTokenDecodingError(sprintf("Invalid JSON returned while decoding section %s ; an array must be provided", $key));
|
|
}
|
|
}
|
|
else {
|
|
throw new JsonWebTokenDecodingError(sprintf("An error occured while decoding a base64 string from section %s", $key));
|
|
}
|
|
}
|
|
|
|
JsonWebTokenValidate::validateSignature($this->header['alg'], $this->secretKey, $encodedHeader, $encodedPayload, $signature);
|
|
}
|
|
catch(\Throwable $t) {
|
|
throw new JsonWebTokenDecodingError($t->getMessage(), $t->getCode(), $t);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public static function base64url_decode($data) : string|false
|
|
{
|
|
return base64_decode(strtr($data, '-_', '+/'));
|
|
}
|
|
|
|
public function decode() : bool
|
|
{
|
|
return $this->parse();
|
|
}
|
|
|
|
/**
|
|
* Basic validation of JWT encoded string
|
|
* @return bool
|
|
*/
|
|
public function isJWT() : bool
|
|
{
|
|
try {
|
|
return $this->parse();
|
|
}
|
|
catch(\Throwable $t) {}
|
|
|
|
return false;
|
|
}
|
|
|
|
public function getPayload() : array
|
|
{
|
|
return $this->payload;
|
|
}
|
|
} |