From bbd3f00e5c1f303176745684045ea96ef3c2b8c3 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 22 May 2023 11:55:41 -0700 Subject: [PATCH] feat: add decodeHeaderAndPayload method --- src/JWT.php | 46 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/JWT.php b/src/JWT.php index c83ff099..f5fae425 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -79,7 +79,7 @@ class JWT * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' * and 'RS512'. * - * @return stdClass The JWT's payload as a PHP object + * @return stdClass The JWT's header and payload as PHP objects * * @throws InvalidArgumentException Provided key/key-array was empty or malformed * @throws DomainException Provided JWT is malformed @@ -92,7 +92,7 @@ class JWT * @uses jsonDecode * @uses urlsafeB64Decode */ - public static function decode( + public static function decodeHeaderAndPayload( string $jwt, $keyOrKeyArray ): stdClass { @@ -167,7 +167,47 @@ public static function decode( throw new ExpiredException('Expired token'); } - return $payload; + $decodedJwt = new stdClass(); + $decodedJwt->header = $header; + $decodedJwt->payload = $payload; + + return $decodedJwt; + } + + /** + * Decodes the payload from a JWT string into a PHP object. + * + * @param string $jwt The JWT + * @param Key|ArrayAccess|array $keyOrKeyArray The Key or associative array of key IDs + * (kid) to Key objects. + * If the algorithm used is asymmetric, this is + * the public key. + * Each Key object contains an algorithm and + * matching key. + * Supported algorithms are 'ES384','ES256', + * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' + * and 'RS512'. + * + * @return stdClass The JWT's payload as a PHP object + * + * @throws InvalidArgumentException Provided key/key-array was empty or malformed + * @throws DomainException Provided JWT is malformed + * @throws UnexpectedValueException Provided JWT was invalid + * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed + * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' + * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' + * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode( + string $jwt, + $keyOrKeyArray + ): stdClass { + $decodedJwt = self::decodeHeaderAndPayload($jwt, $keyOrKeyArray); + + return $decodedJwt->payload; } /**