Skip to main content

Fixed: "DomainException: Unknown JSON error: 7" from JWT::encode in php-jwt

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

firebase/php-jwt's JWT::encode stopped with DomainException: Unknown JSON error: 7 when one of the claims was NAN, the result of fdiv() dividing zero by zero. Error 7 is PHP's JSON_ERROR_INF_OR_NAN: JSON has no way to write NAN or INF. Check the number with is_finite() before it goes into a claim.

What I Was Doing​

I was checking which PHP values php-jwt 7.2.2 writes into custom claims, for posts about custom claims in PHP. Strings, integers, floats, booleans and arrays all went into the token. Then I tried a float that isn't a finite number: NAN.

The example below shows it on its own. A photo app puts the share of her storage that Ada has used into her token, as storage_used. Ada's plan has no storage yet, so the share is fdiv(0, 0), which is NAN. fdiv() is PHP's division that follows the IEEE 754 standard for floating-point numbers: the PHP manual says "If the num2 is zero, then one of INF, -INF, or NAN will be returned."

What I Expected​

A token with a storage_used claim, or an error that names the value php-jwt can't write.

What Happened Instead​

Create a folder named demo and install php-jwt in it:

Terminal
mkdir demo
cd demo
composer require firebase/php-jwt

composer require installs php-jwt, version 7.2.2 here, and writes the autoloader that the code loads.

Then the program, in main.php:

main.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
$key = base64_decode('C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=', true);

$usedGb = 0;
$quotaGb = 0; // Ada's plan has no storage yet

$payload = [
'sub' => 'ada',
'storage_used' => fdiv($usedGb, $quotaGb), // the share of her storage Ada has used
];
$token = JWT::encode($payload, $key, 'HS256');

// The payload is the token's middle piece, base64url-encoded JSON.
echo JWT::urlsafeB64Decode(explode('.', $token)[1]) . "\n";

It signs a token with sub and storage_used, then prints the token's payload: the middle piece of the token, decoded from base64url.

In the demo folder, run it:

Terminal
php main.php
Output
PHP Fatal error: Uncaught DomainException: Unknown JSON error: 7 in /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php:544
Stack trace:
#0 /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php(415): Firebase\JWT\JWT::handleJsonError(7)
#1 /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php(240): Firebase\JWT\JWT::jsonEncode(Array)
#2 /Users/Shared/you/demo/main.php(20): Firebase\JWT\JWT::encode(Array, Object(SensitiveParameterValue), 'HS256')
#3 {main}
thrown in /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php on line 544

Fatal error: Uncaught DomainException: Unknown JSON error: 7 in /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php:544
Stack trace:
#0 /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php(415): Firebase\JWT\JWT::handleJsonError(7)
#1 /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php(240): Firebase\JWT\JWT::jsonEncode(Array)
#2 /Users/Shared/you/demo/main.php(20): Firebase\JWT\JWT::encode(Array, Object(SensitiveParameterValue), 'HS256')
#3 {main}
thrown in /Users/Shared/you/demo/vendor/firebase/php-jwt/src/JWT.php on line 544

A zsh terminal where php main.php stops with PHP Fatal error: Uncaught DomainException: Unknown JSON error: 7 in php-jwt's JWT.php, with a stack trace through handleJsonError, jsonEncode and encode, shown twice.

The command is the same in zsh, bash and PowerShell. JWT::encode threw a DomainException with the message Unknown JSON error: 7, and nothing caught it, so PHP stopped the script. The stack trace shows the path, read from the bottom: line 20 of main.php called JWT::encode, which called JWT::jsonEncode, which called JWT::handleJsonError(7). php-jwt marks the key with PHP's #[\SensitiveParameter] attribute, so the trace shows Object(SensitiveParameterValue) instead of the key.

The error appears twice because this PHP's settings both log errors to the terminal, as PHP Fatal error:, and display them, as Fatal error:.

What I Checked​

  • What error 7 is. In a separate script, json_encode(['ratio' => NAN]) failed in the same way, and then json_last_error() returned 7 and json_last_error_msg() returned Inf and NaN cannot be JSON encoded. The PHP manual's list of JSON constants names the code JSON_ERROR_INF_OR_NAN: "The value passed to json_encode() includes either NAN or INF."
  • Why JSON can't hold it. RFC 8259, the JSON standard, says in section 6: "Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted."
  • INF. INF, which fdiv(12, 0) returns, gave the same Unknown JSON error: 7.
  • The code. In php-jwt 7.2.2's JWT.php, JWT::jsonEncode calls json_encode and passes any error code to JWT::handleJsonError. That method has messages for five codes: JSON_ERROR_DEPTH, JSON_ERROR_STATE_MISMATCH, JSON_ERROR_CTRL_CHAR, JSON_ERROR_SYNTAX and JSON_ERROR_UTF8. Every other code becomes Unknown JSON error: and the number.
  • PHP's message is still there. In a catch block right after JWT::encode threw, json_last_error_msg() still returned Inf and NaN cannot be JSON encoded, because no other JSON call had run since php-jwt's.
  • The newest code. The php-jwt repository is now a read-only copy of the Jwt folder in googleapis/google-cloud-php, which takes its issues. The main branch there has the same handleJsonError, and it gave the same message.

So the value is the problem, and php-jwt's message hides PHP's explanation of it. I reported the message as googleapis/google-cloud-php#9904.

The Fix​

Work out the number first, and add the claim only when it's a finite number:

main.php that starts the payload with sub, works out storageUsed with fdiv, adds the storage_used claim only when is_finite says the share is a finite number, then signs the token and prints its payload.

main.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
$key = base64_decode('C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=', true);

$usedGb = 0;
$quotaGb = 0; // Ada's plan has no storage yet

$payload = ['sub' => 'ada'];
$storageUsed = fdiv($usedGb, $quotaGb); // the share of her storage Ada has used
// JSON has no NAN or INF, so add the claim only when the share is a finite number.
if (is_finite($storageUsed)) {
$payload['storage_used'] = $storageUsed;
}
$token = JWT::encode($payload, $key, 'HS256');

// The payload is the token's middle piece, base64url-encoded JSON.
echo JWT::urlsafeB64Decode(explode('.', $token)[1]) . "\n";
  • $payload = ['sub' => 'ada']; starts the payload with the claims every token has.
  • $storageUsed = fdiv($usedGb, $quotaGb); works out the share in its own variable, before anything goes into the payload.
  • if (is_finite($storageUsed)) adds storage_used only when the share is a finite number. The PHP manual says: "A finite float is neither NAN (is_nan()), nor infinite (is_infinite())."

The Result​

Run it again:

Terminal
php main.php
Output
{"sub":"ada"}

A zsh terminal where php main.php prints a payload with only sub set to ada, without a storage_used claim.

The token has no storage_used claim, because Ada has no share to report. In another run, with 12 GB used of a 50 GB plan, the same code printed {"sub":"ada","storage_used":0.24}.

Common Mistakes​

MistakeWhat happensDo this instead
Putting the result of fdiv() straight into a claimDividing by zero gives NAN, INF or -INF, and JWT::encode stops with Unknown JSON error: 7Check the number with is_finite() first
Switching from / to fdiv() to get rid of a DivisionByZeroErrorThe error moves to JWT::encode, with a less helpful messageDecide in your own code what the claim holds when the divisor is zero
Looking for Unknown JSON error: 7 in php-jwt's documentationphp-jwt has no message for that codeLook the code up in PHP's JSON constants, or print json_last_error_msg() in the catch block

Troubleshooting​

SymptomLikely causeFix
DomainException: Unknown JSON error: 7 from JWT::encodeA claim's value is NAN, INF or -INFCheck numbers with is_finite() before adding them
DomainException: Unknown JSON error: 8 from JWT::encodeA claim's value is a resource, such as an open filePut the data in the claim, not the handle
DomainException: Unknown JSON error: 6 from JWT::encodeThe payload array holds a reference to itselfBuild the payload from plain values
DivisionByZeroError: Division by zero/ divided by zeroCheck the divisor before you divide

FAQ​

Is this a bug in php-jwt?​

The value is the problem: JSON has no way to write NAN or INF, so they can't go into a token's payload as valid JSON. php-jwt's part is the message, which shows only the error code. googleapis/google-cloud-php#9904 asks for PHP's own message instead.

Why does the example use fdiv() and not /?​

Because / throws when it divides by zero: 0 / 0 stops with DivisionByZeroError: Division by zero. The PHP manual says it "is thrown when an attempt is made to divide a number by zero." fdiv() returns INF, -INF or NAN instead. Either way, the code has to decide what a share of nothing means.

Can php-jwt write something else in place of NAN?​

No. JWT::jsonEncode passes only JSON_UNESCAPED_SLASHES to json_encode, so you can't add a flag such as JSON_PARTIAL_OUTPUT_ON_ERROR. That flag would write 0 in place of NAN or INF anyway, which is a wrong number. Decide in your own code what the claim holds.

Do other JWT libraries stop too?​

Not all of them. Python's PyJWT writes NaN into the payload, which isn't JSON, and the token then fails in other languages' libraries: see Fixed: JWT Claims Set Must Be a Top-Level JSON Object in jose for a PyJWT Token.

Conclusion​

php-jwt's Unknown JSON error: 7 is PHP's JSON_ERROR_INF_OR_NAN: a claim holds NAN or INF, which JSON can't write. Check numbers with is_finite() before they go into a claim, and leave the claim out when they aren't finite.

Additional Resources​