Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
}
}