From fb85f47cfaeffdd94faf8defdf07164abcdad6c3 Mon Sep 17 00:00:00 2001 From: Pinchon Karim Date: Tue, 13 Jun 2023 18:35:01 +0200 Subject: [PATCH] feat: allow get headers when decoding token (#442) Co-authored-by: Vishwaraj Anand Co-authored-by: Brent Shaffer --- README.md | 6 ++++++ src/JWT.php | 7 ++++++- tests/JWTTest.php | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b07aa7d..f2cc5d03 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,14 @@ $payload = [ */ $jwt = JWT::encode($payload, $key, 'HS256'); $decoded = JWT::decode($jwt, new Key($key, 'HS256')); +print_r($decoded); + +// Pass a stdClass in as the third parameter to get the decoded header values +$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers = new stdClass()); +print_r($headers); print_r($decoded); +print_r($headers); /* NOTE: This will now be an object instead of an associative array. To get diff --git a/src/JWT.php b/src/JWT.php index 7e190a3e..7ffb9852 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -78,6 +78,7 @@ class JWT * Supported algorithms are 'ES384','ES256', * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' * and 'RS512'. + * @param stdClass $headers Optional. Populates stdClass with headers. * * @return stdClass The JWT's payload as a PHP object * @@ -94,7 +95,8 @@ class JWT */ public static function decode( string $jwt, - $keyOrKeyArray + $keyOrKeyArray, + stdClass &$headers = null ): stdClass { // Validate JWT $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; @@ -111,6 +113,9 @@ public static function decode( if (null === ($header = static::jsonDecode($headerRaw))) { throw new UnexpectedValueException('Invalid header encoding'); } + if ($headers !== null) { + $headers = $header; + } $payloadRaw = static::urlsafeB64Decode($bodyb64); if (null === ($payload = static::jsonDecode($payloadRaw))) { throw new UnexpectedValueException('Invalid claims encoding'); diff --git a/tests/JWTTest.php b/tests/JWTTest.php index a5721d98..7d49bf04 100644 --- a/tests/JWTTest.php +++ b/tests/JWTTest.php @@ -397,4 +397,19 @@ public function testEncodeDecodeWithResource() $this->assertSame('bar', $decoded->foo); } + + public function testGetHeaders() + { + $payload = [ + 'message' => 'abc', + 'exp' => time() + JWT::$leeway + 20, // time in the future + ]; + $headers = new stdClass(); + + $encoded = JWT::encode($payload, 'my_key', 'HS256'); + JWT::decode($encoded, new Key('my_key', 'HS256'), $headers); + + $this->assertEquals($headers->typ, 'JWT'); + $this->assertEquals($headers->alg, 'HS256'); + } }