Skip to main content

How to Verify a JWT in PHP with firebase/php-jwt

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

JWT::decode from the firebase/php-jwt package verifies a JSON Web Token in PHP. You give it the token and a Key object that pairs the secret with the algorithm, and it returns the claims as an object, or throws an exception that says what's wrong.

Syntax​

Syntax
$claims = JWT::decode(<token>, new Key(<key>, '<algorithm>'));
PartWhat it does
<token>The JWT string to check.
new Key(<key>, '<algorithm>')The key to check the signature with, and the one algorithm it may be used with, such as 'HS256'.
$claimsThe verified claims, as a stdClass object: $claims->sub, $claims->exp and so on.

The doc comment on JWT::decode in the php-jwt source: "Decodes a JWT string into a PHP object." Its signature is decode(string $jwt, $keyOrKeyArray, ?stdClass &$headers = null): stdClass, where the second argument is "The Key or associative array of key IDs (kid) to Key objects".

The Example​

The example signs a token for the user ada with the role reader, then decodes it twice: with the key that signed it, and with a different key, the way a token from another app would arrive.

Both keys are 32 random bytes, made with openssl rand -base64 32 and written as base64. They sit in the code only so the example runs as it is. A real application loads its key from configuration and never keeps it in the source.

Prerequisites​

  • PHP and Composer. This guide uses PHP 8.6.0 and Composer 2.11.3.

Step 1: Create the Project​

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

composer require creates composer.json, downloads php-jwt, v7.2.2 here, into vendor/ and writes the autoloader.

Step 2: Write the Code​

Create main.php:

main.php, which signs a token for ada with role reader and a 10-minute expiry, decodes it with JWT::decode and a Key for HS256, echoes the subject and role, then decodes it with another key inside try and catch for SignatureInvalidException and echoes Rejected with the message.

main.php
<?php

declare(strict_types=1);

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

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

// Two keys, 32 random bytes each, written as base64.
// They're in the code only for this example; a real app loads its key from its configuration.
$key = base64_decode('VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=', true);
$otherKey = base64_decode('rAAk7yhJl8rF7vvQeKOeI2ooYrBw9A45aLuMb44gH78=', true);

$token = JWT::encode(['sub' => 'ada', 'role' => 'reader', 'exp' => time() + 600], $key, 'HS256');

$claims = JWT::decode($token, new Key($key, 'HS256'));
echo "{$claims->sub} {$claims->role}\n";

try {
JWT::decode($token, new Key($otherKey, 'HS256'));
} catch (SignatureInvalidException $e) {
echo "Rejected: {$e->getMessage()}\n";
}

The first JWT::decode gets the key that signed the token, the second $otherKey, so the signature check fails and php-jwt throws SignatureInvalidException.

Step 3: Run It​

Terminal
php main.php
Output
ada reader
Rejected: Signature verification failed

A zsh terminal where php main.php prints ada reader, then Rejected: Signature verification failed.

With the right key, decode checked the signature and the exp claim and returned the claims. With the other key, the signature didn't match, so it threw.

The Exceptions It Throws​

These came from real runs. The first two are php-jwt's own classes, and both extend PHP's UnexpectedValueException, so one catch (UnexpectedValueException $e) covers all of them:

What's wrongExceptionMessage
Signed with another key, or the payload was changedFirebase\JWT\SignatureInvalidExceptionSignature verification failed
The token has expiredFirebase\JWT\ExpiredExceptionExpired token
Signed with HS256, but the Key says 'HS512'UnexpectedValueExceptionIncorrect key for this algorithm
Not a JWT at allUnexpectedValueExceptionWrong number of segments
The key passed as a plain string, not a KeyUnexpectedValueException"kid" empty, unable to lookup correct key

Allow a Little Clock Skew​

JWT::$leeway sets a margin, in seconds, for the time checks. With JWT::$leeway = 60; before decode, a token that had expired 30 seconds earlier still decoded. It's a static property, so it applies to every later decode call too.

Common Mistakes​

MistakeWhat happensDo this instead
Passing the secret itself as the second argumentUnexpectedValueException: "kid" empty, unable to lookup correct keyWrap it: new Key($key, 'HS256')
Catching only SignatureInvalidExceptionAn expired or malformed token throws something else and stops the scriptCatch UnexpectedValueException for every bad token
Trusting the header to pick the algorithmphp-jwt doesn't allow it: the Key fixes the algorithmKeep the algorithm in your code, in the Key

Troubleshooting​

SymptomLikely causeFix
Signature verification failedAnother key signed it, or it was changedCheck with the signing key; reject the token
Expired tokenThe exp has passedGet a new token, or set a small JWT::$leeway
Incorrect key for this algorithmThe token's algorithm differs from the Key'sSign and verify with the same algorithm

FAQ​

Why does decode return an object, not an array?​

It decodes the JSON payload into a stdClass, which is what PHP's JSON decoding gives for objects. Read claims as properties, $claims->sub.

Can I read the header without verifying?​

The README says no: "Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by this library." To get the header, pass a stdClass object as the third argument, $headers = new stdClass();, and read it after decode returns: it held {"typ":"JWT","alg":"HS256","kid":"key-2026-11"} for a token with a key ID. A null variable stays null.

Conclusion​

JWT::decode($token, new Key($key, 'HS256')) verifies the signature and the time claims and returns the claims as an object. The Key pins the algorithm, and one catch (UnexpectedValueException $e) rejects every bad token.

Additional Resources​