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: 9 additions & 0 deletions src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ public static function encode(
if ($keyId !== null) {
$header['kid'] = $keyId;
}
if (isset($payload['nbf']) && !\is_numeric($payload['nbf'])) {
throw new UnexpectedValueException('Payload nbf must be a number');
}
if (isset($payload['iat']) && !\is_numeric($payload['iat'])) {
throw new UnexpectedValueException('Payload iat must be a number');
}
if (isset($payload['exp']) && !\is_numeric($payload['exp'])) {
throw new UnexpectedValueException('Payload exp must be a number');
}
$segments = [];
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
Expand Down
39 changes: 39 additions & 0 deletions tests/JWTTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,45 @@ public function testDecodeExpectsIntegerExp()
JWT::decode($payload, $this->hmacKey);
}

public function testEncodeThrowsWhenIatIsNotNumeric(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Payload iat must be a number');

JWT::encode(['iat' => 'not-an-int'], $this->hmacKey->getKeyMaterial(), 'HS256');
}

public function testEncodeThrowsWhenNbfIsNotNumeric(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Payload nbf must be a number');

JWT::encode(['nbf' => 'not-an-int'], $this->hmacKey->getKeyMaterial(), 'HS256');
}

public function testEncodeThrowsWhenExpIsNotNumeric(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Payload exp must be a number');

JWT::encode(['exp' => 'not-an-int'], $this->hmacKey->getKeyMaterial(), 'HS256');
}

public function testEncodeAcceptsNumericStringTimestamps(): void
{
$payload = [
'message' => 'abc',
'iat' => (string) time(),
'exp' => (string) (time() + 20),
'nbf' => (string) (time() - 20),
];

$encoded = JWT::encode($payload, $this->hmacKey->getKeyMaterial(), 'HS256');
$decoded = JWT::decode($encoded, $this->hmacKey);

$this->assertSame('abc', $decoded->message);
}

public function testRsaKeyLengthValidationThrowsException(): void
{
$this->expectException(DomainException::class);
Expand Down
Loading