Luminova Framework

PHP Luminova: Sign and Validate JWT

Last updated: 2026-11-28 20:57:12

JSON Web Token signing and validation in Luminova, including key configuration, token claims, and optional server-side storage.

Luminova’s JWT class signs and verifies JSON Web Tokens through the firebase/php-jwt package. By default, it uses HS256 and derives the signing key from the application key and the supplied user identifier. Create a separate instance for each user when relying on derived keys.


Token Claims

Custom values passed to encode() are stored under data. The helper also includes these claims.

ClaimMeaning
uid, subUser ID as supplied and as a string, respectively. Use string user IDs when issuing tokens for validate().
iat, expIssued-at and expiration timestamps.
iss, audIssuer and audience values configured when constructing the helper.
fmv, app, verFramework version, application name, and application version.
jti, roleOptional token identifier and role supplied to encode().
dataCustom application payload.

Examples

Issue a Token

Generate the token after your application authenticates the user. Keep the application key on the server.

use Luminova\Security\JWT;

$jwt = new JWT(
    algo: 'HS256',
    iss: 'https://example.com',
    aud: 'https://example.com/api'
);

$token = $jwt->encode(['plan' => 'standard'], 'user-1042', expiry: 3600);

JWT::getInstance() reuses the same helper. Its configuration arguments apply when it first creates the instance.


Validate a Token in API Middleware

Pass the authorization header and the expected string user identifier from your application’s authentication flow. This example checks application-specific issuer and audience values before accepting the request. Apply your application’s access rules after these checks.

use Luminova\Security\JWT;
use Luminova\Exceptions\EncryptionException;

function acceptsApiToken(string $authorization, string $expectedUserId): bool
{
    if ($authorization === '' || $expectedUserId === '') {
        return false;
    }

    try {
        return (new JWT())->validate(
            $authorization,
            $expectedUserId,
            static function (bool $valid, object $claims): bool {
                return $valid
                    && $claims->iss === 'https://example.com'
                    && $claims->aud === 'https://example.com/api';
            }
        );
    } catch (EncryptionException) {
        return false;
    }
}

Inspect Validation Errors

Read getError() after a failed operation. Error objects can include the submitted token, so keep them out of client responses and avoid logging the token itself.


Store and Validate a Token

Use sign() to encode and store a token under writeable/auth/jwt/. Check its return value before trying to read the file.

use Luminova\Security\JWT;

$jwt = new JWT();
$userId = 'user-1042';

$path = $jwt->sign(['plan' => 'standard'], $userId, expiry: 3600);

if ($path !== null) {
    $valid = $jwt->validateFromFile($userId);
}

Class Definition


Methods

__construct

Create a JWT helper.

public function __construct(
    protected ?string $algo = null,
    protected ?string $salt = null,
    protected ?string $iss = null,
    protected ?string $aud = null
)

Parameters:

ParameterTypeDescription
$algo?stringSigning algorithm. Defaults to HS256.
$salt?stringOptional prefix for key derivation.
$iss?stringIssuer claim. Defaults to APP_URL.
$aud?stringAudience claim. Defaults to APP_URL . '/api'.

getInstance

Get the shared JWT helper. Configuration applies on first use.

public static function getInstance(
    ?string $algo = null,
    ?string $salt = null,
    ?string $iss = null,
    ?string $aud = null
): self

Parameters:

ParameterTypeDescription
$algo?stringSigning algorithm. Defaults to HS256.
$salt?stringOptional prefix for key derivation.
$iss?stringIssuer claim. Defaults to APP_URL.
$aud?stringAudience claim. Defaults to APP_URL . '/api'.

Return:

self - The shared instance.


isValidToken

Validate a supplied token or read the stored token when the argument is omitted.

public static function isValidToken(string|int $userId, ?string $token = null): bool

Parameters:

ParameterTypeDescription
$userIdstring|intUser identifier. Use a string when issuing tokens for identity validation.
$token?stringJWT or authorization header value. Defaults to null.

Return:

bool - Whether validation succeeded. Exceptions are reported as false.


hasError

Check whether the helper has a recorded error.

public function hasError(): bool

Return:

bool - Whether an error is recorded.


getError

Get the last recorded error.

public function getError(): ?object

Return:

object{code:int,error:string,uid:string|int,token:?string}|null - The error details or null.


getPayload

Read the payload saved by the most recent operation. Omit the property name for the full object.

public function getPayload(?string $property = null): ?object

Parameters:

ParameterTypeDescription
$property?stringName of an object-valued member such as data. Defaults to null.

Return:

?object - The full payload or an object-valued member, or null if absent.


getKey

Read the key currently held by the helper.

public function getKey(): OpenSSLAsymmetricKey|OpenSSLCertificate|string|null

Return:

OpenSSLAsymmetricKey|OpenSSLCertificate|string|null - The signing or verification key, or null before one is set or derived.


getUserToken

Read a user’s stored JWT.

public function getUserToken(string|int $userId, ?string $filename = null): string

Parameters:

ParameterTypeDescription
$userIdstring|intUser identifier. Use a string when issuing tokens for identity validation.
$filename?stringOptional stored token filename. Defaults to the user’s hashed filename.

Return:

string - The stored token.

Throws:


setKey

Set a key explicitly for a signing or verification operation. Match the key type to the configured algorithm.

public function setKey(OpenSSLAsymmetricKey|OpenSSLCertificate|string $key): self

Parameters:

ParameterTypeDescription
$keyOpenSSLAsymmetricKey|OpenSSLCertificate|stringKey for the current operation.

Return:

self - The current helper.


encode

Sign the payload and application claims.

public function encode(
    array $payload,
    string|int $userId,
    int $expiry = 3600,
    ?string $tokenId = null,
    string|int|null $role = null
): ?string

Parameters:

ParameterTypeDescription
$payloadarray<string,mixed>Custom values written to the data claim.
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.
$expiryintLifetime in seconds. Defaults to 3600.
$tokenId?stringOptional JWT ID.
$rolestring&#124;int&#124;nullOptional role claim.

Return:

?string - The signed JWT or null.

Throws:


decode

Verify and decode a token with the configured algorithm and key. Use validate() to match the user identity.

public function decode(string $token, string|int $userId): ?object

Parameters:

ParameterTypeDescription
$tokenstringSigned JWT.
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.

Return:

?object - Normalized claims or null.

Throws:


validate

Verify a JWT and compare its user ID with the expected ID. Check issuer and audience in your callback if your application depends on those claims.

public function validate(?string $token, string|int $userId, ?Closure $callback = null): bool

Parameters:

ParameterTypeDescription
$token?stringJWT or authorization header value. Pass null to use the stored token.
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.
$callback?ClosureOptional callback receiving a validity flag and a payload or error object.

Return:

bool - Whether validation passed, or the callback’s result when invoked.

Throws:


validateFromFile

Read a stored token and validate its user identity.

public function validateFromFile(
    string|int $userId,
    ?string $filename = null,
    ?Closure $callback = null
): bool

Parameters:

ParameterTypeDescription
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.
$filename?stringOptional stored token filename. Defaults to the user’s hashed filename.
$callback?ClosureOptional callback receiving a validity flag and a payload or error object.

Return:

bool - Whether validation passed, or the callback’s result when invoked.

Throws:


hashFilename

Derive the default storage filename from the user identifier using XXH3.

public static function hashFilename(string|int $userId): string

Parameters:

ParameterTypeDescription
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.

Return:

string - The hashed filename with a .key extension.

Throws:


key

Derive a user-specific key with an HMAC using the application key.

public static function key(string|int $userId, string $algo = 'sha256', ?string $salt = null): string

Parameters:

ParameterTypeDescription
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.
$algostringHMAC algorithm. Defaults to sha256.
$salt?stringOptional key prefix.

Return:

string - The derived key.

Throws:


sign

Encode a token and store it on the server.

public function sign(
    array $payload,
    string|int $userId,
    int $expiry = 2592000,
    ?string $filename = null
): ?string

Parameters:

ParameterTypeDescription
$payloadarray<string,mixed>Custom values written to the data claim.
$userIdstring&#124;intUser identifier. Use a string when issuing tokens for identity validation.
$expiryintLifetime in seconds. Defaults to 2592000.
$filename?stringOptional stored token filename. Defaults to the user’s hashed filename.

Return:

?string - The stored token’s path, or null if no file was stored.

Throws:


store

Write an already encoded token to the JWT storage directory.

public function store(string $filename, string $token): bool

Parameters:

ParameterTypeDescription
$filenamestringStorage filename.
$tokenstringSigned JWT.

Return:

bool - Whether the token was written.

Throws: