PHP Luminova: Sign and Validate JWT
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.
| Claim | Meaning |
|---|---|
uid, sub | User ID as supplied and as a string, respectively. Use string user IDs when issuing tokens for validate(). |
iat, exp | Issued-at and expiration timestamps. |
iss, aud | Issuer and audience values configured when constructing the helper. |
fmv, app, ver | Framework version, application name, and application version. |
jti, role | Optional token identifier and role supplied to encode(). |
data | Custom 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
- Full namespace:
Luminova\Security\JWT - This class implements Luminova\Interface\LazyObjectInterface.
- This class is final.
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:
| Parameter | Type | Description |
|---|---|---|
$algo | ?string | Signing algorithm. Defaults to HS256. |
$salt | ?string | Optional prefix for key derivation. |
$iss | ?string | Issuer claim. Defaults to APP_URL. |
$aud | ?string | Audience 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
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$algo | ?string | Signing algorithm. Defaults to HS256. |
$salt | ?string | Optional prefix for key derivation. |
$iss | ?string | Issuer claim. Defaults to APP_URL. |
$aud | ?string | Audience 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$token | ?string | JWT 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(): boolReturn:
bool - Whether an error is recorded.
getError
Get the last recorded error.
public function getError(): ?objectReturn:
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): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$property | ?string | Name 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|nullReturn:
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$filename | ?string | Optional stored token filename. Defaults to the user’s hashed filename. |
Return:
string - The stored token.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe token file is missing or unreadable.
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | OpenSSLAsymmetricKey|OpenSSLCertificate|string | Key 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
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$payload | array<string,mixed> | Custom values written to the data claim. |
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$expiry | int | Lifetime in seconds. Defaults to 3600. |
$tokenId | ?string | Optional JWT ID. |
$role | string|int|null | Optional role claim. |
Return:
?string - The signed JWT or null.
Throws:
- Luminova\Exceptions\EncryptionExceptionSigning or key derivation fails.
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): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$token | string | Signed JWT. |
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
Return:
?object - Normalized claims or null.
Throws:
- Luminova\Exceptions\EncryptionExceptionVerification, decoding, or key derivation fails.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$token | ?string | JWT or authorization header value. Pass null to use the stored token. |
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$callback | ?Closure | Optional callback receiving a validity flag and a payload or error object. |
Return:
bool - Whether validation passed, or the callback’s result when invoked.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe user identifier is invalid or token processing fails.
validateFromFile
Read a stored token and validate its user identity.
public function validateFromFile(
string|int $userId,
?string $filename = null,
?Closure $callback = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$filename | ?string | Optional stored token filename. Defaults to the user’s hashed filename. |
$callback | ?Closure | Optional callback receiving a validity flag and a payload or error object. |
Return:
bool - Whether validation passed, or the callback’s result when invoked.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe user identifier is invalid or token processing fails.
hashFilename
Derive the default storage filename from the user identifier using XXH3.
public static function hashFilename(string|int $userId): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
Return:
string - The hashed filename with a .key extension.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe user identifier is invalid.
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$algo | string | HMAC algorithm. Defaults to sha256. |
$salt | ?string | Optional key prefix. |
Return:
string - The derived key.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe user identifier or application key is missing.
sign
Encode a token and store it on the server.
public function sign(
array $payload,
string|int $userId,
int $expiry = 2592000,
?string $filename = null
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$payload | array<string,mixed> | Custom values written to the data claim. |
$userId | string|int | User identifier. Use a string when issuing tokens for identity validation. |
$expiry | int | Lifetime in seconds. Defaults to 2592000. |
$filename | ?string | Optional 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:
- Luminova\Exceptions\EncryptionExceptionToken encoding fails.
store
Write an already encoded token to the JWT storage directory.
public function store(string $filename, string $token): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | Storage filename. |
$token | string | Signed JWT. |
Return:
bool - Whether the token was written.
Throws:
- Luminova\Exceptions\EncryptionExceptionThe token could not be saved.