Skip to content

Core\Jwt\KeySet::read

Reads a JSON Web Key Set (JWKS), the list of public keys a login service publishes. It returns a Core\Jwt\KeySet that you pass to Core\Jwt::verifyIssued to check the tokens of that service.

Each key in the list usually has a name in kid. A token names its key in the same way, so verifyIssued uses exactly that one key. A token with no kid works only with a set that has exactly one key.

read skips a key it does not use, for example a key for encryption. It throws a RuntimeError when the whole document is wrong: it is not JSON, it has no keys list, two keys have the same name, it contains a private key, or it has more than 16 keys. The message says what is wrong, because the document comes from a service you chose.

The examples below read a key set with two keys, show the errors for a wrong document, and load the key set of a login service from a file when a program starts.

Parameters

  • $jwksstringThe document as the issuer published it. This method only reads it. Fetching, caching and replacing the keys is the job of a package. The method keeps no state between calls.

Options

  • rsaSchemeCore\Crypto\KeyKindoptionalThe scheme for an RSA key that has no alg: RsaPkcs1 for RS256 or RsaPss for PS256. A key's own alg always wins. An RSA key with neither is not allowed, and the method does not guess. Other kinds of key have their own algorithm, so this option does not change them.

Return value

Returns Core\Jwt\KeySet. A set of at most 16 public keys, each with the name the document gave it. A key is found in it by its kid. The set is never searched by trying every key.

Errors

  • LogicError{ rsaScheme: … } names a kind that is not one of the two RSA kinds. No other kind has two schemes to choose from.
  • RuntimeError$jwks is not a valid key document. It is not JSON, or it has no keys array. A key has a private field, or a kid that is not a string. A key does not match its kind, such as an RSA modulus outside 2048 to 8192 bits. An alg does not fit its key's kind. Two keys have the same kid. The document has more than 16 keys that can be used. The document is longer than 1 MiB.

Examples

Basics

<?nvs
// Shows how to read a key set with two keys and check tokens signed with each one.
// A login service has two key pairs, `blue` and `green`.
Core\Crypto\KeyPair $blue = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
Core\Crypto\KeyPair $green = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::P256);
// `write` gives a public key as a JWK, a JSON object. The service adds a name in `kid`
// and publishes both keys in one document.
string $blueJwk = Core\Encoding::decodeText($blue->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);
string $greenJwk = Core\Encoding::decodeText($green->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);
string $jwks = "{\"keys\":["
. Core\Str::replace($blueJwk, '{', "{\"kid\":\"blue\",")
. ','
. Core\Str::replace($greenJwk, '{', "{\"kid\":\"green\",")
. ']}';
// `read` checks the document and returns a `Core\Jwt\KeySet`.
Core\Jwt\KeySet $keys = Core\Jwt\KeySet::read($jwks);
// Each token names its key in `kid`. `verifyIssued` uses that key from the set.
// This prints `ada` and then `grace`.
array<string> $names = ['blue' => 'ada', 'green' => 'grace'];
foreach ($names as string $kid => string $name) {
Core\Crypto\KeyPair $pair = $kid == 'blue' ? $blue : $green;
string $token = Core\Jwt::signObject(
Core\Arr::shapeAs<{ iss: string, aud: string, sub: string }>([
'iss' => 'https://login.example.com',
'aud' => 'shop',
'sub' => $name,
]),
15m,
$pair,
{ kid: $kid },
);
var $claims = Core\Jwt::verifyIssued<tainted { sub: string }>($token, $keys, 'https://login.example.com', 'shop');
echo $claims->sub, "\n";
}
Output
ada
grace

A wrong document

<?nvs
// Shows the errors `read` throws when a document is not a valid key set.
Core\Crypto\KeyPair $pair = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
string $jwk = Core\Encoding::decodeText($pair->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);
string $named = Core\Str::replace($jwk, '{', "{\"kid\":\"main\",");
// Three wrong documents: an HTML error page, JSON with no `keys` list, and two keys
// with the same name. Each one throws a `RuntimeError`, and the message says why.
array<string> $documents = [
'<html>502 Bad Gateway</html>',
"{\"error\":\"not found\"}",
"{\"keys\":[" . $named . ',' . $named . ']}',
];
foreach ($documents as string $document) {
try {
Core\Jwt\KeySet::read($document);
echo 'read', "\n";
} catch (RuntimeError $wrong) {
echo $wrong->message, "\n";
}
}
// A key for encryption has `"use":"enc"`. `read` skips it and reads the other key.
// This prints `read`.
string $forEncryption = Core\Str::replace($jwk, '{', "{\"kid\":\"enc\",\"use\":\"enc\",");
Core\Jwt\KeySet $keys = Core\Jwt\KeySet::read("{\"keys\":[" . $forEncryption . ',' . $named . ']}');
echo 'read', "\n";
Output
Core\Jwt\KeySet::read(): $jwks is not a document to read keys from — it is not JSON. A key this roster has no use for is skipped instead, so what is refused here is the document rather than a key in it.
Core\Jwt\KeySet::read(): $jwks is not a document to read keys from — it carries no `keys` array, which is the one member a JWKS document has (RFC 7517 § 5). A key this roster has no use for is skipped instead, so what is refused here is the document rather than a key in it.
Core\Jwt\KeySet::read(): $jwks is not a document to read keys from — two of its keys are named `main`, so a token asking for that key names two, and which one signed it is not a question a verifier may answer by trying both. A key this roster has no use for is skipped instead, so what is refused here is the document rather than a key in it.
read

A key rotation

<?nvs
// Shows a key rotation: a login service adds a new key, and later removes the old one.
class Keys
{
// Returns the public key as a JWK with the name `$kid`.
public static function jwk(Core\Crypto\KeyPair $pair, string $kid): string
{
string $jwk = Core\Encoding::decodeText($pair->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);
return Core\Str::replace($jwk, '{', "{\"kid\":\"" . $kid . "\",");
}
// Returns `valid` when the set has the key of the token, or `refused` when it does not.
public static function check(string $token, Core\Jwt\KeySet $keys): string
{
try {
Core\Jwt::verifyIssued<tainted { sub: string }>($token, $keys, 'https://login.example.com', 'shop');
return 'valid';
} catch (RuntimeError $invalid) {
return 'refused';
}
}
}
Core\Crypto\KeyPair $old = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
Core\Crypto\KeyPair $new = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
var $claims = Core\Arr::shapeAs<{ iss: string, aud: string, sub: string }>([
'iss' => 'https://login.example.com',
'aud' => 'shop',
'sub' => 'ada',
]);
string $oldToken = Core\Jwt::signObject($claims, 1h, $old, { kid: 'old' });
string $newToken = Core\Jwt::signObject($claims, 1h, $new, { kid: 'new' });
// Step 1: the service publishes both keys. Your program reads the document again,
// so tokens with either key are valid. This prints `valid valid`.
Core\Jwt\KeySet $both = Core\Jwt\KeySet::read("{\"keys\":[" . Keys::jwk($old, 'old') . ',' . Keys::jwk($new, 'new') . ']}');
echo Keys::check($oldToken, $both), ' ', Keys::check($newToken, $both), "\n";
// Step 2: the service removes the old key. A token with the old key is now refused.
// This prints `refused valid`.
Core\Jwt\KeySet $current = Core\Jwt\KeySet::read("{\"keys\":[" . Keys::jwk($new, 'new') . ']}');
echo Keys::check($oldToken, $current), ' ', Keys::check($newToken, $current), "\n";
Output
valid valid
refused valid