- Added JsonWebToken encoder

This commit is contained in:
Dave Mc Nicoll 2024-05-31 19:00:04 +00:00
parent c4e4db7a45
commit e63ea439d6
3 changed files with 43 additions and 5 deletions

View File

@ -8,10 +8,9 @@ class JsonWebTokenDecoder
protected array $payload;
protected JsonWebTokenAlgorithmEnum $algrithm;
public function __construct(
public string $encoded
public string $encoded,
public string $secretKey,
) {}
protected function parse() : bool
@ -42,7 +41,7 @@ class JsonWebTokenDecoder
}
}
JsonWebTokenValidate::validateSignature($this->header['alg'], getenv('LEAN_RANDOM'), $encodedHeader, $encodedPayload, $signature);
JsonWebTokenValidate::validateSignature($this->header['alg'], $this->secretKey, $encodedHeader, $encodedPayload, $signature);
}
catch(\Throwable $t) {
throw new JsonWebTokenDecodingError($t->getMessage(), $t->getCode(), $t);

View File

@ -4,9 +4,48 @@ namespace Ulmus\User\Authorize\Bearer;
class JsonWebTokenEncoder
{
protected string $token;
protected array $header = [
"typ" => "JWT",
];
public function __construct(
public array $payload,
public string $secretKey,
protected JsonWebTokenAlgorithmEnum $algorithm = JsonWebTokenAlgorithmEnum::HS256,
) {
$this->header['alg'] = $this->algorithm->name;
}
public static function base64url_encode($data) : string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
public function encode() : string
{
$jsonHeader = json_encode($this->header);
$jsonPayload = json_encode($this->payload);
$encodedHeader = static::base64url_encode($jsonHeader);
$encodedPayload = static::base64url_encode($jsonPayload);
list($algo, $method, ) = $this->algorithm->phpAlgoMethods();
switch($method) {
case 'hash_hmac':
$signature = hash_hmac($algo, sprintf("%s.%s", $encodedHeader, $encodedPayload), $this->secretKey, true);
break;
}
$this->token = sprintf("%s.%s.%s", $encodedHeader, $encodedPayload, static::base64url_encode($signature));
return $this->getToken();
}
public function getToken() : string
{
return $this->token;
}
}

View File

@ -47,7 +47,7 @@ class BearerMethod implements MethodInterface
public function autodetectTokenType() : BearerTokenTypeEnum
{
$this->jwt = new JsonWebTokenDecoder($this->token);
$this->jwt = new JsonWebTokenDecoder($this->token, getenv('LEAN_RANDOM'));
if ( $this->jwt->isJWT() ) {
return BearerTokenTypeEnum::JsonWebToken;