Core\Jwt::verify
Checks a JSON Web Token (JWT) that your own program signed with Core\Jwt::sign, and returns its claims. You give the token and the same secret key that signed it.
verify checks two things. First, the signature: the token must be signed with this key, and nobody may have changed it. Second, the expiry: the time in the exp claim must not have passed. If one check fails, verify throws a RuntimeError. It never returns an empty or false value, so you cannot forget to check the result.
The claims come back as an array of text, iat and exp included. Each value is tainted, because it came from outside your program. 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 that a changed token throws an error, and find the user of an API request.
Parameters
$tokenstringThe token as the request sent it, in its three-part form.$keysecret bytesThe shared secret that was given tosign, or the issuer's secret. The method compares the token'salgwith the key's algorithm. It never usesalgto choose the algorithm.
Return value
Returns array<tainted string>. Every claim in the payload, by name, and each one is tainted. A signature shows who wrote a value, but not that the value is safe to use. The result includes exp and iat as strings of decimal digits.
Errors
LogicError$keyis shorter than 32 bytes, so it cannot be a signing key.RuntimeErrorThe token was not signed with this key. The message is the same for every reason the signature check fails. It also throws when the token has expired, has noexp, or has a claim that is not a string.
Examples
Basics
<?nvs// Shows how to check a token and read its claims.
// `Core\Crypto::generateKey` returns 32 random secret bytes. They are the key.secret bytes $key = Core\Crypto::generateKey();string $token = Core\Jwt::sign(['sub' => '42', 'plan' => 'pro'], 1h, $key);
// `verify` checks the signature and the expiry with the same key.// It returns every claim as text. This prints `42` and `pro`.array<tainted string> $claims = Core\Jwt::verify($token, $key);echo $claims['sub'], "\n";echo $claims['plan'], "\n";
// `exp` is the expiry, in seconds since 1 January 1970. It comes back as text too.// `as ?int` converts it to a whole number. This prints `3600`, one hour.int $exp = $claims['exp'] as ?int ?? 0;int $iat = $claims['iat'] as ?int ?? 0;echo $exp - $iat, "\n";42pro3600A changed token
<?nvs// Shows that `verify` throws an error for a token somebody changed, and for a token signed// with another key.
secret bytes $key = Core\Crypto::generateKey();string $token = Core\Jwt::sign(['sub' => '42', 'role' => 'reader'], 1h, $key);array<string> $parts = Core\Str::split($token, '.');
// Somebody writes new claims into the middle part and keeps the old signature.bytes $json = Core\Encoding::encodeText("{\"sub\":\"42\",\"role\":\"admin\"}", Core\Charset::Utf8);string $payload = Core\Encoding::toBase64Url($json);string $changed = $parts[0] . '.' . $payload . '.' . $parts[2];
// The signature does not match the new claims, so `verify` throws a `RuntimeError`.// This prints `changed token: refused`.try { Core\Jwt::verify($changed, $key); echo 'changed token: accepted', "\n";} catch (RuntimeError $error) { echo 'changed token: refused', "\n";}
// A token signed with a different key also throws. This prints `other key: refused`.try { Core\Jwt::verify($token, Core\Crypto::generateKey()); echo 'other key: accepted', "\n";} catch (RuntimeError $error) { echo 'other key: refused', "\n";}changed token: refusedother key: refusedAn api request
<?nvs// Shows how an API reads the token from an `Authorization` header and finds the user.
// This method runs on each request. It returns the user's id, or `null` when the token is not valid.// The id is `tainted` because it comes from outside the program.class Auth{ public static function userId(string $header, secret bytes $key): ?tainted string { // The header is `Bearer ` and then the token. // `Core\Str::afterPrefix` returns the token, or `null` when the header does not start with `Bearer `. ?string $token = Core\Str::afterPrefix($header, 'Bearer '); if ($token == null) { return null; } try { array<tainted string> $claims = Core\Jwt::verify($token, $key); return $claims['sub'] as string; } catch (RuntimeError $invalid) { return null; } }}
secret bytes $key = Core\Crypto::generateKey();string $token = Core\Jwt::sign(['sub' => '1042'], 30m, $key);
// A request with a valid token. This prints `user 1042`.?tainted string $user = Auth::userId('Bearer ' . $token, $key);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', $key);echo $nobody == null ? 'no user' : 'user ' . $nobody, "\n";user 1042no user