Skip to content

Commit fb85f47

Browse files
kpn13vishwarajanandbshaffer
authored
feat: allow get headers when decoding token (#442)
Co-authored-by: Vishwaraj Anand <[email protected]> Co-authored-by: Brent Shaffer <[email protected]>
1 parent 398ccd2 commit fb85f47

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

Diff for: README.md

+6
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,14 @@ $payload = [
4545
*/
4646
$jwt = JWT::encode($payload, $key, 'HS256');
4747
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
48+
print_r($decoded);
49+
50+
// Pass a stdClass in as the third parameter to get the decoded header values
51+
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers = new stdClass());
52+
print_r($headers);
4853

4954
print_r($decoded);
55+
print_r($headers);
5056

5157
/*
5258
NOTE: This will now be an object instead of an associative array. To get

Diff for: src/JWT.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class JWT
7878
* Supported algorithms are 'ES384','ES256',
7979
* 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
8080
* and 'RS512'.
81+
* @param stdClass $headers Optional. Populates stdClass with headers.
8182
*
8283
* @return stdClass The JWT's payload as a PHP object
8384
*
@@ -94,7 +95,8 @@ class JWT
9495
*/
9596
public static function decode(
9697
string $jwt,
97-
$keyOrKeyArray
98+
$keyOrKeyArray,
99+
stdClass &$headers = null
98100
): stdClass {
99101
// Validate JWT
100102
$timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
@@ -111,6 +113,9 @@ public static function decode(
111113
if (null === ($header = static::jsonDecode($headerRaw))) {
112114
throw new UnexpectedValueException('Invalid header encoding');
113115
}
116+
if ($headers !== null) {
117+
$headers = $header;
118+
}
114119
$payloadRaw = static::urlsafeB64Decode($bodyb64);
115120
if (null === ($payload = static::jsonDecode($payloadRaw))) {
116121
throw new UnexpectedValueException('Invalid claims encoding');

Diff for: tests/JWTTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -397,4 +397,19 @@ public function testEncodeDecodeWithResource()
397397

398398
$this->assertSame('bar', $decoded->foo);
399399
}
400+
401+
public function testGetHeaders()
402+
{
403+
$payload = [
404+
'message' => 'abc',
405+
'exp' => time() + JWT::$leeway + 20, // time in the future
406+
];
407+
$headers = new stdClass();
408+
409+
$encoded = JWT::encode($payload, 'my_key', 'HS256');
410+
JWT::decode($encoded, new Key('my_key', 'HS256'), $headers);
411+
412+
$this->assertEquals($headers->typ, 'JWT');
413+
$this->assertEquals($headers->alg, 'HS256');
414+
}
400415
}

0 commit comments

Comments
 (0)