Skip to content

Serialization

The RFC7515 (JWS) and RFC7516 (JWE) introduce several serialization modes.

  • Compact
  • JSON Flattened
  • JSON General

The Compact mode is most known and commonly used as it is compact and URL safe i.e. it is designed for web context. JSON Flattened and General are not URL safe, but provides features that may fit your application context.

JWS serialization

JWS compact

This serialization mode is probably the one you know the most. It it a string composed of three parts encoded in Base64 Url Safe and separated by a dot (.).

The serializer class is Jose\Component\Signature\Serializer\CompactSerializer. The associated name is jws_compact.

Example:

eyJhbGciOiJFUzUxMiJ9.UGF5bG9hZA.AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZqwqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8KpEHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn

There are some limitations when you use this serialization mode:

  • Unprotected header not supported.
  • Unencoded payload must contain characters within the following range of ASCII characters: 0x20-0x2d and 0x2f-0x7e

JWS JSON flattened

This serialization mode is useful when you need to use the unprotected header. It it a simple JSON object.

The serializer class is Jose\Component\Signature\Serializer\JSONFlattenedSerializer. The associated name is jws_json_flattened.

Example:

{
  "payload": "SW4gb3VyIHZpbGxhZ2UsIGZvbGtzIHNheSBHb2QgY3J1bWJsZXMgdXAgdGhlIG9sZCBtb29uIGludG8gc3RhcnMu",
  "protected": "eyJhbGciOiJFUzI1NiJ9",
  "header": {
    "kid": "myEcKey"
  },
  "signature": "b7V2UpDPytr-kMnM_YjiQ3E0J2ucOI9LYA7mt57vccrK1rb84j9areqgQcJwOA00aWGoz4hf6sMTBfobdcJEGg"
}

JWS JSON general

This serialization mode is similar to the JWS JSON Flattened, but may contain more than one signature. It it a JSON object.

The serializer class is Jose\Component\Signature\Serializer\JSONGeneralSerializer. The associated name is jws_json_general.

Example:

{
  "payload": "SW4gb3VyIHZpbGxhZ2UsIGZvbGtzIHNheSBHb2QgY3J1bWJsZXMgdXAgdGhlIG9sZCBtb29uIGludG8gc3RhcnMu",
  "signatures": [
    {
      "protected": "eyJhbGciOiJSUzI1NiJ9",
      "header": {
        "kid": "myRsaKey"
      },
      "signature": "B04c24gSnpVm1Z-_bemfyNMCpZm6Knj1yB-yzaIOvijsWfDgoF_mSJccTIbzapNgwJudnobr5iDOfZWiRR9iqCyDJLe5M1S40vFF7MFEI3JecYRgrRc6n1lTkYLMRyVq48BwbQlmKgPqmK9drun3agklsr0FmgNx65pfmcnlYdXsgwxf8WbgppefrlrMImp-98-dNtBcUL8ce1aOjbcyVFjGMCzpm3JerQqIzWQvEwBstnMEQle73KHcyx_nsTmlzY70CaydbRTsciOATL7WfiMwuX1q9Y2NIpTg3CbOTWKdwjh7iyfiAKQxNBaF2mApnqj9hjpf8GwR-CfxAzJtPg"
    },
    {
      "protected": "eyJhbGciOiJFUzI1NiJ9",
      "header": {
        "kid": "myEcKey"
      },
      "signature": "2cbugKq0ERaQMh01n2B-86EZFYleeMf8bsccaQMxzOxAg14PxfjR3IImvodTJYqkmfBJYW203etz2-7ZtJUOGw"
    },
    {
      "protected": "eyJhbGciOiJIUzI1NiJ9",
      "header": {
        "kid": "myMacKey"
      },
      "signature": "e7R9gjx0RsUNa3c7qd8k9mQGEhtcG8vsN1W7jbLb2MA"
    }
  ]
}

JWS serializer manager

The serializer manager can be helpful when your application deals more than one serialization mode.

<?php

require_once 'vendor/autoload.php';

use Jose\Component\Signature\Serializer;

$manager = new Serializer\JWSSerializerManager([
    new Serializer\CompactSerializer(),
    new Serializer\JSONFlattenedSerializer(),
    new Serializer\JSONGeneralSerializer(),
]);

// Serializes the second signature (index = 1) of the variable $jws (JWS object) into JSON Flattened serialization mode.
$token = $manager->serialize('jws_json_flattened', $jws, 1);

// Retrieve the JWS object from a token, along with the name of the serializer that read it
$result = $manager->unserializeToken($token);

$jws  = $result->getJws();
$name = $result->getSerializerName(); // e.g. "jws_json_flattened"

JWE serialization

JWE compact

This serialization mode is probably the one you know the most. It it a string composed of five parts encoded in Base64 Url Safe and separated by a dot (.).

The serializer class is Jose\Component\Encryption\Serializer\CompactSerializer. The associated name is jwe_compact.

Example:

eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.9hH0vgRfYgPnAHOd8stkvw

There are some limitations when you use this serialization mode:

  • No Additional Authentication Data can be used.
  • No shared unprotected header or per-recipient header can be used.

JWE JSON flattened

This serialization mode is useful when you need to use the unprotected header. It it a simple JSON object.

The serializer class is Jose\Component\Encryption\Serializer\JSONFlattenedSerializer. The associated name is jwe_json_flattened.

Example:

{
  "protected":"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
  "unprotected":{"jku":"https://server.example.com/keys.jwks"},
  "header":{"alg":"A128KW","kid":"7"},
  "encrypted_key":"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ",
  "iv":"AxY8DCtDaGlsbGljb3RoZQ",
  "ciphertext":"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",
  "tag":"Mz-VPPyU4RlcuYv1IwIvzw"
}

JWE JSON general

This serialization mode is similar to the JWE JSON Flattened, but may contain more than one recipient. It it a JSON object.

The serializer class is Jose\Component\Encryption\Serializer\JSONGeneralSerializer. The associated name is jwe_json_general.

Example:

 {
  "protected":"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
  "unprotected":{"jku":"https://server.example.com/keys.jwks"},
  "recipients":[
    {
      "header":{"alg":"RSA1_5","kid":"2011-04-29"},
      "encrypted_key":"UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A"
    },
    {
      "header":{"alg":"A128KW","kid":"7"},
      "encrypted_key":"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ"
    }
  ],
  "iv":"AxY8DCtDaGlsbGljb3RoZQ",
  "ciphertext":"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",
  "tag":"Mz-VPPyU4RlcuYv1IwIvzw"
 }

JWE serializer manager

The serializer manager can be helpful when your application deals more than one serialization mode.

<?php

require_once 'vendor/autoload.php';

use Jose\Component\Encryption\Serializer;

$manager = new Serializer\JWESerializerManager([
    new Serializer\CompactSerializer(),
    new Serializer\JSONFlattenedSerializer(),
    new Serializer\JSONGeneralSerializer(),
]);

// Serializes the second recipient (index = 1) of the variable $jwe (JWE object) into JSON Flattened serialization mode.
$token = $manager->serialize('jwe_json_flattened', $jwe, 1);

// Retrieve the JWE object from a token, along with the name of the serializer that read it
$result = $manager->unserializeToken($token);

$jwe  = $result->getJwe();
$name = $result->getSerializerName(); // e.g. "jwe_json_flattened"

Bounded JSON decoding

Since 4.2.6, the JWS and JWE serializers bound the JSON they decode before handing it to json_decode(). They count the brackets ([), braces ({) and commas (,) found outside the string literals of a document, which bounds the number of values and members it can hold. All the JSON documents of one token share a budget of 4,096: the token itself in the JSON serializations, and each of its protected headers. A token beyond that budget is rejected before json_decode() runs on the document that exceeds it.

The content of the strings is not counted: a large payload, an unencoded (b64: false) payload or a long x5c chain costs nothing. A protected header usually holds a few dozen values, and a signature or recipient entry five to ten, so the budget leaves room for hundreds of signatures or recipients. To limit their number, set the maximum number of signatures or recipients of the loader.

The budget only applies to the documents of the tokens, and to those of an SD-JWT, which share one budget with its Disclosures. The key sets loaded from a jku or x5u URL, and the claims your application decodes once the token is verified or decrypted, are not limited.

Rejections for a bound

A document is also rejected when it is nested more deeply than json_decode() reads: 511 levels of arrays and objects, the document itself being the first.

Since 4.3, the serializers name the bound that a token goes beyond, with a Jose\Component\Core\Exception\JsonBoundExceededException:

Bound Message
More than 4,096 JSON values The JSON documents of the token hold more JSON values than the 4096 that are decoded.
More than 511 levels A JSON document of the token is nested too deeply.

The values are counted before a document is decoded, so a document beyond both bounds is reported for its values. The JSON serializers throw the JsonBoundExceededException itself. The compact serializers throw an InvalidSerializationException with the same message, and chain it. Invalid JSON is still rejected with Unsupported input., or Unsupported input by the compact serializers.

Before 4.3, both bounds gave the messages of invalid JSON, and the JSON serializers threw an InvalidArgumentException for them. JsonBoundExceededException extends it, so the catch blocks written for previous versions keep matching.

The serializer managers throw Unsupported input. whatever the cause, and the loaders chain that exception in their own. To tell a token beyond a bound apart from a malformed one, walk the chain:

<?php

use Jose\Component\Core\Exception\JoseException;
use Jose\Component\Core\Exception\JsonBoundExceededException;

try {
    $result = $jwsLoader->loadAndVerify($token, $jwkset);
} catch (JoseException $throwable) {
    for ($cause = $throwable; $cause !== null; $cause = $cause->getPrevious()) {
        if ($cause instanceof JsonBoundExceededException) {
            $this->logger->warning('A token beyond the bounds of the JSON decoder was rejected.', [
                'bound' => $cause->getMessage(),
            ]);
            break;
        }
    }

    throw $throwable;
}

Reading a token without knowing its mode

unserializeToken() tries every serializer it holds and returns an UnserializationResult carrying both the token object and the name of the serializer that could read it. When none of them can, it throws Unsupported input. and chains the exception of the last serializer it tried. That serializer may not be the one of the format of the token: when the JSON serializers come after the compact one, a compact token with a malformed protected header gets their rejection, invalid JSON, as its cause. Since 4.3, a token rejected for a bound of the JSON decoder is the exception: the manager chains the rejection of the serializer that met the bound, whichever serializer came last.

Warning

unserialize() used to write that name into a variable of the caller:

$jws = $manager->unserialize($token, $name); // Deprecated since 4.3

Passing the $name argument is deprecated since 4.3 and the argument is removed in 5.0. Calling unserialize($token) without it stays valid.