Skip to content

Commit

Permalink
feat: allow typ header override (#546)
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer authored Nov 28, 2023
1 parent f03270e commit 79cb30b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,14 @@ public static function encode(
string $keyId = null,
array $head = null
): string {
$header = ['typ' => 'JWT', 'alg' => $alg];
$header = ['typ' => 'JWT'];
if (isset($head) && \is_array($head)) {
$header = \array_merge($header, $head);
}
$header['alg'] = $alg;
if ($keyId !== null) {
$header['kid'] = $keyId;
}
if (isset($head) && \is_array($head)) {
$header = \array_merge($head, $header);
}
$segments = [];
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
Expand Down
22 changes: 22 additions & 0 deletions tests/JWTTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -518,4 +518,26 @@ public function testGetHeaders()
$this->assertEquals($headers->typ, 'JWT');
$this->assertEquals($headers->alg, 'HS256');
}

public function testAdditionalHeaderOverrides()
{
$msg = JWT::encode(
['message' => 'abc'],
'my_key',
'HS256',
'my_key_id',
[
'cty' => 'test-eit;v=1',
'typ' => 'JOSE', // override type header
'kid' => 'not_my_key_id', // should not override $key param
'alg' => 'BAD', // should not override $alg param
]
);
$headers = new stdClass();
JWT::decode($msg, new Key('my_key', 'HS256'), $headers);
$this->assertEquals('test-eit;v=1', $headers->cty, 'additional field works');
$this->assertEquals('JOSE', $headers->typ, 'typ override works');
$this->assertEquals('my_key_id', $headers->kid, 'key param not overridden');
$this->assertEquals('HS256', $headers->alg, 'alg param not overridden');
}
}

0 comments on commit 79cb30b

Please sign in to comment.