Core\Jwt::verifyIssued
Core\Jwt::verifyIssued<T>(
string $token,
Core\Jwt\KeySet|Core\Crypto\PublicKey $keys,
string $issuer,
string $audience,
{…},
): TChecks a JSON Web Token (JWT) that another service signed, such as a login provider, and returns its claims as a type you choose. You give the token, the service's public key or its published key set, the issuer you expect and the audience you expect.
verifyIssued checks the token in a fixed order. It checks the signature first. Only a token with a valid signature gets the next checks: the expiry and start time, then the iss claim (who issued the token) and the aud claim (who the token is for). If one check fails, it throws a RuntimeError. All signature failures give the same message, so an attacker learns nothing from it. It never returns an empty or false value.
The claims come back as the type between < and >, in the same way as Core\Json::decodeAs. Its text properties must be tainted. A valid signature proves who wrote a claim, not that it is safe to use in HTML or SQL.
The examples below read the claims of a token, show a token for another application being refused, and find the user of a request with the key set a login service publishes.
Parameters
$tokenstringThe token as the request sent it, in its three-part form. A token longer than 8 KiB throws an error and is not read.$keysCore\Jwt\KeySet|Core\Crypto\PublicKeyThe issuer's key set, in which the header'skidnames exactly one key. It can also be one public key. The method never tries every key. A token without akidis checked only against a set with exactly one key. The method compares the token'salgwith the key's algorithm. It never usesalgto choose the algorithm.$issuerstringWhat the token'sissmust equal, exactly.$audiencestringWhat the token'saudmust be, or must contain. A token with more than one audience must also have anazpequal to this value.
Options
leewayCore\Time\DurationoptionalHow much the clocks may differ, at the start and at the end of the valid time. It is 60 seconds if you leave it out. A negative value or more than 5 minutes throws an error. It makes the expiry check less strict, but never turns it off.typstringoptionalThetypthe header must have. The comparison ignores case and anapplication/prefix. RFC 9068's access tokens useat+jwt. If you leave it out, anytypis allowed.noncestringoptionalThe value the token'snonceclaim must equal. It is compared in constant time. If you give it, a token without anoncethrows an error.maxAgeCore\Time\DurationoptionalHow old the token'sauth_timemay be. If you give it, a token without anauth_timethrows an error.
Return value
Returns T. An object of the type you wrote, decoded from the payload the way Core\Json::decodeAs decodes a document. Its string properties must be declared tainted, or the call does not compile. A signature shows who wrote a claim, but not that the claim is safe to use.
Errors
LogicErrorleewayis negative or more than 5 minutes. The type you wrote is a list, and a token's payload is never a list. The key is anX25519key, which cannot verify a signature.RuntimeErrorThe token was not signed with this issuer's key. Its header has a parameter that is not allowed, or no key matches it. The message is the same for all of these. It also throws when a valid token is outside its valid time. A registered claim with the wrong value throws too, and the message names the claim.
Examples
Basics
<?nvs// Shows how to check a token that another service signed, and read its claims.
// The other service has a key pair. It signs the token with the private key.Core\Crypto\KeyPair $service = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);string $token = Core\Jwt::signObject( Core\Arr::shapeAs<{ iss: string, aud: string, sub: string }>([ 'iss' => 'https://login.example.com', 'aud' => 'shop', 'sub' => 'ada', ]), 15m, $service,);
// Your program has only the public key. `verifyIssued` checks the signature, the expiry,// the issuer (`iss`) and the audience (`aud`). It returns the type between `<` and `>`.var $claims = Core\Jwt::verifyIssued<tainted { sub: string, iat: int, exp: int }>( $token, $service->publicKey(), 'https://login.example.com', 'shop',);
// This prints `ada`.echo $claims->sub, "\n";// `iat` and `exp` are times in seconds. This prints `900`, which is 15 minutes.echo $claims->exp - $claims->iat, "\n";ada900A token for another app
<?nvs// Shows that a token for another application throws an error, and a changed token too.
Core\Crypto\KeyPair $service = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
// The login service signs a token for the application `blog`.string $token = Core\Jwt::signObject( Core\Arr::shapeAs<{ iss: string, aud: string, sub: string }>([ 'iss' => 'https://login.example.com', 'aud' => 'blog', 'sub' => 'ada', ]), 15m, $service,);
// This program is the application `shop`. The signature is valid, but the `aud`// claim is `blog`, so `verifyIssued` throws a `RuntimeError`. The message names the claim.try { var $claims = Core\Jwt::verifyIssued<tainted { sub: string }>( $token, $service->publicKey(), 'https://login.example.com', 'shop', ); echo 'accepted: ', $claims->sub, "\n";} catch (RuntimeError $refused) { echo $refused->message, "\n";}
// Somebody adds one character to the end of the token. The signature no longer// matches, so `verifyIssued` throws a `RuntimeError` again. This prints `refused`.string $changed = $token . 'x';try { Core\Jwt::verifyIssued<tainted { sub: string }>( $changed, $service->publicKey(), 'https://login.example.com', 'blog', ); echo 'accepted', "\n";} catch (RuntimeError $refused) { echo 'refused', "\n";}Core\Jwt::verifyIssued(): the token is authentic and its `aud` does not name `shop` — or it names several audiences and its `azp` is not this one. A claim this member checks is one the issuer and this program had to agree on beforehand, so a mismatch is a token meant for somebody else rather than a forgery.refusedA login with a key set
<?nvs// Shows how an API finds the user of a request with the keys a login service publishes.
// A login service publishes its public keys as a JSON key set (JWKS). Each key has// a name in `kid`. Here the service has an old key `2025` and a new key `2026`.Core\Crypto\KeyPair $old = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);Core\Crypto\KeyPair $new = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);string $oldJwk = Core\Encoding::decodeText($old->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);string $newJwk = Core\Encoding::decodeText($new->publicKey()->write(Core\Crypto\PublicKey::Format::Jwk), Core\Charset::Utf8);string $jwks = "{\"keys\":[" . Core\Str::replace($oldJwk, '{', "{\"kid\":\"2025\",") . ',' . Core\Str::replace($newJwk, '{', "{\"kid\":\"2026\",") . ']}';
// Your program reads the key set once, when it starts.Core\Jwt\KeySet $keys = Core\Jwt\KeySet::read($jwks);
// This method runs on each request. It returns the user's id, or `null` when the// token is not valid. The token's `kid` selects the key from the set.class Auth{ public static function userId(string $header, Core\Jwt\KeySet $keys): ?tainted string { ?string $token = Core\Str::afterPrefix($header, 'Bearer '); if ($token == null) { return null; } try { var $claims = Core\Jwt::verifyIssued<tainted { sub: string }>( $token, $keys, 'https://login.example.com', 'shop', ); return $claims->sub; } catch (RuntimeError $invalid) { return null; } }}
// The login service signs a token with its new key and names that key in `kid`.string $token = Core\Jwt::signObject( Core\Arr::shapeAs<{ iss: string, aud: string, sub: string }>([ 'iss' => 'https://login.example.com', 'aud' => 'shop', 'sub' => '1042', ]), 1h, $new, { kid: '2026' },);
// A request with that token. This prints `user 1042`.?tainted string $user = Auth::userId('Bearer ' . $token, $keys);echo $user == null ? 'no user' : 'user ' . $user, "\n";
// A request with a broken token. This prints `no user`.?tainted string $nobody = Auth::userId('Bearer abc.def.ghi', $keys);echo $nobody == null ? 'no user' : 'user ' . $nobody, "\n";user 1042no user