Skip to content

Commit

Permalink
feat: allow get headers when decoding token (#442)
Browse files Browse the repository at this point in the history
Co-authored-by: Vishwaraj Anand <[email protected]>
Co-authored-by: Brent Shaffer <[email protected]>
  • Loading branch information
3 people authored Jun 13, 2023
1 parent 398ccd2 commit fb85f47
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand All @@ -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;
Expand All @@ -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');
Expand Down
15 changes: 15 additions & 0 deletions tests/JWTTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}

0 comments on commit fb85f47

Please sign in to comment.