-WIP on Bearer token
This commit is contained in:
1 parent
0657622eab
commit
c4e4db7a45
13 files changed
+377
-35
No files matched your search
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Ulmus\User\Authorize\Bearer;
|
||||
|
||||
class JsonWebTokenDecoder
|
||||
{
|
||||
protected array $header;
|
||||
|
||||
protected array $payload;
|
||||
|
||||
protected JsonWebTokenAlgorithmEnum $algrithm;
|
||||
|
||||
public function __construct(
|
||||
public string $encoded
|
||||
) {}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
$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'], getenv('LEAN_RANDOM'), $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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user