Skip to main content

How to Add Custom Claims to a JWT in PHP with php-jwt

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

With firebase/php-jwt, a custom claim is one more key in the payload array you pass to JWT::encode. A string, a list and a set of keys and values become a JSON string, array and object, and JWT::decode gives them back as a string, a PHP array and a stdClass object.

Syntax​

Syntax
$payload = [
'<registered claim>' => <value>,
'<custom claim>' => <value>,
];
$token = JWT::encode($payload, <key>, '<alg>');

$claims = JWT::decode($token, new Key(<key>, '<alg>'));
$value = $claims->{'<custom claim>'};
PartWhat it does
'<registered claim>'A claim the JWT standard defines, such as sub or exp.
'<custom claim>'A name of your own: a short one such as name, or a URL on your own domain so that it can't collide with anyone else's.
<value>A string, a number, a boolean, null, a list such as ['editor', 'viewer'], or keys and values such as ['albums' => 10].
JWT::encode(...)Signs the payload with the key and returns the token.
JWT::decode(...)Verifies the token and returns its claims as a stdClass object.
$claims->{'<custom claim>'}Reads a claim. The braces and quotes are needed when the name isn't a valid PHP name, such as a URL.

RFC 7519, the JWT standard, says that "Claim Names can be defined at will by those using JWTs", and that to prevent collisions a new name should be registered with IANA or be "a value that contains a Collision-Resistant Name", such as a URL on a domain you control. The php-jwt README notes that the decoded claims are "an object instead of an associative array".

The Example​

The example signs a token for Ada at a photo site. Besides four registered claims, it carries three custom claims of three kinds: name, a string; roles, a list; and https://photos.example.org/quota, a set of keys and values, named with a URL on the site's own domain. The code prints the token and its payload, then verifies the token and reads one value of each kind.

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 installs php-jwt, version 7.2.2 here, and writes the autoloader that the code loads.

Step 2: Write the Code​

Create main.php:

main.php, which builds a payload with iss, sub, aud and exp plus the custom claims name, roles and https://photos.example.org/quota, signs it with JWT::encode, prints the token and its payload, then decodes it and prints the name, the roles joined with a comma and the number of albums.

main.php
<?php

declare(strict_types=1);

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

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

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
$key = base64_decode('C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=', true);

$payload = [
'iss' => 'https://login.example.org',
'sub' => 'ada',
'aud' => 'https://photos.example.org',
'exp' => time() + 3600,
'name' => 'Ada', // a string
'roles' => ['editor', 'viewer'], // a list: an array
'https://photos.example.org/quota' => ['albums' => 10, 'storage_gb' => 50], // keys and values: an object
];
$token = JWT::encode($payload, $key, 'HS256');
echo $token . "\n";

// The payload is the token's middle piece, base64url-encoded JSON.
echo JWT::urlsafeB64Decode(explode('.', $token)[1]) . "\n";

$claims = JWT::decode($token, new Key($key, 'HS256'));
$quota = $claims->{'https://photos.example.org/quota'};
echo $claims->name . ' | ' . implode(', ', $claims->roles) . ' | ' . $quota->albums . "\n";
  • 'name' => 'Ada' is a string claim.
  • 'roles' => ['editor', 'viewer'] is a list: an array whose keys are 0, 1 and so on, which php-jwt writes as a JSON array.
  • 'https://photos.example.org/quota' => [...] has string keys, so php-jwt writes it as a JSON object. Its name is a URL on the photo site's own domain.
  • $claims->{'https://photos.example.org/quota'} reads the claim whose name is a URL: a quoted string in braces after ->.
  • $quota->albums reads a value inside it, because the nested object comes back as a stdClass object too.

Step 3: Run It​

Terminal
php main.php
Output
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJleHAiOjE3OTYyOTgyNjIsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9fQ.2Mn9A8_3Qem__ihhFRVoqyigFu3ddfHMRZxxQQnLeg8
{"iss":"https://login.example.org","sub":"ada","aud":"https://photos.example.org","exp":1796298262,"name":"Ada","roles":["editor","viewer"],"https://photos.example.org/quota":{"albums":10,"storage_gb":50}}
Ada | editor, viewer | 10

A zsh terminal where php main.php prints the token, then its payload with iss, sub, aud, exp, name Ada, roles editor and viewer, and the quota object with albums 10 and storage_gb 50, then Ada, editor, viewer and 10 separated by bars.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • php-jwt wrote each claim as its JSON type: "name":"Ada", "roles":["editor","viewer"] and "https://photos.example.org/quota":{"albums":10,"storage_gb":50}.
  • JWT::decode verified the signature and exp, and returned the claims as an object. The list came back as a PHP array, which implode joined, and the quota came back as a stdClass object, read with ->albums.
  • The URL-named claim needed braces, because a URL isn't a valid PHP property name.

In separate checks, a float, a boolean and an integer claim came back with their types, 2.5, true and 10, and a null value went into the token as "plan":null.

Common Mistakes​

MistakeWhat happensDo this instead
Reading a nested claim like an array, as in $quota['albums']Fatal error: Uncaught Error: Cannot use object of type stdClass as arrayRead it with ->albums
A list with a gap in its keys, such as one left by unsetphp-jwt writes it as an object: {"0":"editor","2":"admin"}Pass it through array_values first, which gave ["editor","admin"]
An empty array for a claim that holds keys and values[] is written as [], a JSON array, not {}Use (object) [], which is written as {}
A DateTimeImmutable as a claim's valuephp-jwt writes {"date":"2026-01-02 03:04:05.000000","timezone_type":3,"timezone":"UTC"}Write the time as Unix seconds with ->getTimestamp()
NAN or INF as a claim's valueJWT::encode stops with DomainException: Unknown JSON error: 7Check the number with is_finite() first

Troubleshooting​

SymptomLikely causeFix
Warning: Undefined property: stdClass::$planThe token has no plan claimAdd a fallback: $claims->plan ?? 'free'
Cannot use object of type stdClass as arrayA nested claim read with square bracketsUse ->
DomainException: Unknown JSON error: 7 from JWT::encodeA claim's value is NAN or INF, which JSON can't holdCheck the number with is_finite() before adding the claim
DomainException: Malformed UTF-8 characters from JWT::encodeA string claim holds bytes that aren't valid UTF-8Make sure the text is UTF-8 before it goes into a claim

FAQ​

How do I get the claims as an array?​

The php-jwt README casts them: (array) $claims. That converts only the top level: in my check, the quota claim inside stayed a stdClass object. For arrays all the way down, json_decode(json_encode($claims), true) worked: the quota claim came back as an array, with albums set to 10.

Should every custom claim be named with a URL?​

No. A URL on your own domain is for claims that other services might name the same way. RFC 7519 also allows Private Names that only the token's producer and consumer agree on, such as name and roles here, but it warns that, unlike public names, they're "subject to collision and should be used with caution".

Where do the registered claims come from?​

They're ordinary keys too: iss, sub, aud and exp in the example. JWT::decode checks exp, nbf and iat, but it doesn't check iss or aud.

Conclusion​

In php-jwt, custom claims are keys in the payload array, and their PHP values become JSON strings, arrays and objects. Name a claim with a URL on your own domain when it might collide, read it back with braces after ->, and remember that nested claims come back as stdClass objects, not arrays.

Additional Resources​