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 typ override header #546

Merged
merged 1 commit into from
Nov 28, 2023
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');
}
}
Loading