Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow get headers when decoding token #442

Merged
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');
}
}