65 lines
2.4 KiB
PHP
65 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\User\Authorize\Bearer;
|
|
|
|
abstract class JsonWebTokenValidate
|
|
{
|
|
public static function validateHeaderAlgorithm(array $header) : void
|
|
{
|
|
if (! array_key_exists('alg', $header)) {
|
|
throw new JsonWebTokenDecodingError("Your header data is missing a valid algorithm (alg).");
|
|
}
|
|
|
|
if ( ! JsonWebTokenAlgorithmEnum::exists($header['alg']) ) {
|
|
throw new JsonWebTokenDecodingError(
|
|
sprintf("Given algorithm '%s' is not supported. Please try with one of the above : %s", $header['alg'], implode(', ', JsonWebTokenAlgorithmEnum::list()))
|
|
);
|
|
}
|
|
}
|
|
|
|
public static function validateHeaderType(array $header) : void
|
|
{
|
|
if ( array_key_exists('typ', $header) && ! JsonWebTokenTypeEnum::exists($header['typ']) ) {
|
|
throw new JsonWebTokenDecodingError(
|
|
sprintf("Given type '%s' is not supported. Please try with one of the above : %s", $header['typ'], implode(', ', JsonWebTokenTypeEnum::list()))
|
|
);
|
|
}
|
|
}
|
|
|
|
public static function validatePayloadExpiration(array $payload) : void
|
|
{
|
|
if ( array_key_exists('exp', $payload) && ( $payload['exp'] < time() ) ) {
|
|
throw new JsonWebTokenDecodingError(
|
|
sprintf("Given token is expired (%s)", ( new \DateTime())->setTimestamp($payload['exp'])->format(\DateTime::ISO8601) )
|
|
);
|
|
}
|
|
}
|
|
|
|
public static function validateSignature(string $alg, string $secret, string $encodedHeader, string $encodedPayload, string $encodedSignature) : void
|
|
{
|
|
$algorithm = JsonWebTokenAlgorithmEnum::fromString($alg);
|
|
|
|
static::validateAlgorithm($algorithm);
|
|
|
|
$decodedSignature = JsonWebTokenDecoder::base64url_decode($encodedSignature);
|
|
|
|
list($algo, $method, ) = $algorithm->phpAlgoMethods();
|
|
|
|
switch($method) {
|
|
case 'hash_hmac':
|
|
$compare = hash_hmac($algo, sprintf("%s.%s", $encodedHeader, $encodedPayload), $secret, true);
|
|
break;
|
|
}
|
|
|
|
if ( ($compare ?? null) !== $decodedSignature) {
|
|
throw new JsonWebTokenDecodingError(
|
|
sprintf("Given signature (%s) do not match computed signature (%s)", $encodedSignature, JsonWebTokenEncoder::base64url_encode($compare))
|
|
);
|
|
}
|
|
}
|
|
|
|
public static function validateAlgorithm(JsonWebTokenAlgorithmEnum $algorithm) : void
|
|
{
|
|
$algorithm->assessOperability();
|
|
}
|
|
} |