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
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,15 @@ $payload = [
* for a list of spec-compliant algorithms.
*/
$jwt = JWT::encode($payload, $key, 'HS256');
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
/**
* Providing headers is optional. If provided with an instantiated object,
* headers will be populated.
*/
$headers = new stdClass();
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers);
vishwarajanand marked this conversation as resolved.
Show resolved Hide resolved

print_r($decoded);
print_r($headers);

/*
NOTE: This will now be an object instead of an associative array. To get
Expand Down
6 changes: 5 additions & 1 deletion src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,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 +112,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');
}
}