Skip to content

feat: Allow object as payload #574

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 7 additions & 6 deletions src/JWT.php
Original file line number Diff line number Diff line change
@@ -184,7 +184,7 @@ public static function decode(
/**
* Converts and signs a PHP array into a JWT string.
*
* @param array<mixed> $payload PHP array
* @param array<mixed>|object $payload PHP array or object
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
@@ -197,7 +197,7 @@ public static function decode(
* @uses urlsafeB64Encode
*/
public static function encode(
array $payload,
array|object $payload,
$key,
string $alg,
string $keyId = null,
@@ -379,13 +379,13 @@ public static function jsonDecode(string $input)
/**
* Encode a PHP array into a JSON string.
*
* @param array<mixed> $input A PHP array
* @param array<mixed>|object $input A PHP array or object
*
* @return string JSON representation of the PHP array
* @return string JSON representation of the PHP array or object
*
* @throws DomainException Provided object could not be encoded to valid JSON
*/
public static function jsonEncode(array $input): string
public static function jsonEncode(array|object $input): string
{
if (PHP_VERSION_ID >= 50400) {
$json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
@@ -399,7 +399,8 @@ public static function jsonEncode(array $input): string
throw new DomainException('Null result with non-null input');
}
if ($json === false) {
throw new DomainException('Provided object could not be encoded to valid JSON');
$type = is_array($input) ? 'array' : 'object';
throw new DomainException('Provided ' . $type . ' could not be encoded to valid JSON');
}
return $json;
}
11 changes: 11 additions & 0 deletions tests/JWTTest.php
Original file line number Diff line number Diff line change
@@ -82,6 +82,17 @@ public function testValidToken()
$this->assertSame($decoded->message, 'abc');
}

public function testValidTokenWithObjectPayload()
{
$payload = (object)[
'message' => 'abc',
'exp' => time() + JWT::$leeway + 20, // time in the future
];
$encoded = JWT::encode($payload, 'my_key', 'HS256');
$decoded = JWT::decode($encoded, new Key('my_key', 'HS256'));
$this->assertSame($decoded->message, 'abc');
}

/**
* @runInSeparateProcess
*/