JWT
JWT
JWT-based auth session backend.
class JWT implements \Hazaar\Auth\Interface\SessionBackend , \Hazaar\Auth\Interface\RevocableSessionBackend , \Hazaar\Auth\Interface\DeviceListableSessionBackendImplements: Hazaar\Auth\Interface\SessionBackend, Hazaar\Auth\Interface\RevocableSessionBackend, Hazaar\Auth\Interface\DeviceListableSessionBackend
Implements Hazaar\Auth\Interface\SessionBackend using signed JSON Web Tokens as the session transport format. Session state is encoded into token claims and validated on load with configurable signature algorithms and keys.
Supported capabilities:
- HMAC (
HS*) and OpenSSL-backed asymmetric algorithms (RS*,ES*,PS*) - Configurable issuer/expiry and optional key files
- Optional device fingerprint claim binding (
fp) - In-memory session data access through the SessionBackend API
The access token is a signed JWT, but the refresh token deliberately is not: it's opaque, store-backed, and rotated on every use via Hazaar\Auth\Interface\RefreshTokenStore (default Hazaar\Auth\Store\File\RefreshTokenStore), the same rationale as Hazaar\OAuth\Server's refresh tokens — unlike the access token, it's only ever presented back to this backend and must be revocable. Configure the store via the refresh_tokens (class name or instance) and refresh_tokens_options config keys.
The default store is local to one instance/container's runtime directory — a token minted by one instance isn't redeemable via another. A horizontally-scaled deployment (multiple app instances behind a load balancer) should configure refresh_tokens to Hazaar\Auth\Store\Cache\RefreshTokenStore with a shared cache backend (redis/memcached) instead.
Properties
config
public Options $configType: Hazaar\Auth\Session\Backend\JWT\Options
privateKey
public string $privateKeyType: string
publicKey
public string $publicKeyType: string
identity
public string $identityType: string
data
public array $dataType: array
refreshTokenStore
public RefreshTokenStore $refreshTokenStoreType: Hazaar\Auth\Interface\RefreshTokenStore
pendingRefreshCarryForward
public array $pendingRefreshCarryForwardType: array
privateKeyCache
Cached list of private keys.
private array $privateKeyCacheType: array
publicKeyCache
Cached list of public keys.
private array $publicKeyCacheType: array
defaultPassphrase
Default passphrase for HMAC signing when not explicitly configured.
private string $defaultPassphrase = 'hazaar_default_jwt_passphrase_change_me'Type: string
Methods
__construct
Constructor for the JWT session backend.
public __construct(array|Options $config): voidLoads cryptographic keys for signing and verification.
NOTES: Issuer used to be generated here based on the application URL if it was not set in the config, but this caused issues in some environments where the application URL is not reliably detected due to the $_SERVER['SERVER_PORT'] not being correct during the bootstrap phase.
To avoid this issue, the 'issuer' configuration is now generated at the time of use if the 'issuer' config value is not set. This allows the application URL to be reliably detected at the time of token generation and validation, while still allowing for a default issuer value if it is not explicitly configured.
Parameters
| Parameter | Type | Description |
|---|---|---|
$config | array | Hazaar\Auth\Session\Backend\JWT\Options |
isEmpty
Indicates whether there is an active authenticated session identity.
public isEmpty(): boolReturns: bool
read
Reads and returns the session data.
public read(): arrayReturns: array
has
Checks if a specific key exists in the session backend.
public has(string $key): boolReturns: bool
This method checks for the existence of a key within the JWT payload. If the key is 'identity', it checks the top-level 'identity' claim. For all other keys, it checks within the nested 'data' claim.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | the key to check for |
get
Retrieves a value from the session backend.
public get(string $key): mixedReturns: mixed
If the key is 'identity', the identity data is returned. Otherwise, the value associated with the key in the data array is returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | the key of the value to retrieve |
set
Sets a value in the JWT payload.
public set(string $key, mixed $value): voidReturns: void
This method stores a key-value pair in the 'data' section of the JWT payload. It specifically prevents overwriting the 'identity' key, which is reserved. If a value is successfully set, it flags the middleware to write the cookie.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | the key to set in the payload |
$value | mixed | the value to store |
Unsets a value from the session backend.
public (string $key): voidReturns: void
This method removes the value associated with the specified key from the session backend. Note that the 'identity' key is protected and cannot be unset.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | the key of the value to unset |
clear
Clears the JWT session backend.
public clear(): voidReturns: void
This method checks if the session backend is not empty. If it contains data, it resets the internal data to null and sets a flag on the middleware to clear the associated cookie.
reset
Resets in-memory identity/data state without touching any persisted storage.
public reset(): voidReturns: void
JWTs are stateless tokens, so this is equivalent to Hazaar\Auth\Session\Backend\JWT::clear for this backend, but is called at the end of every request (not just on logout) to prevent a reused backend instance from leaking one request's identity into the next.
getToken
Generates a JWT token and optionally a refresh token.
public getToken(): ?ExpiringTokenReturns: Hazaar\Auth\ExpiringToken
This method constructs the JWT payload by merging existing data with standard claims such as issuer ('iss'), issued at ('iat'), expiration ('exp'), and subject ('sub'). It then builds the primary access token.
If a refresh timeout is configured, it also generates a refresh token with an extended expiration time, signed with a specific refresh token key.
Additionally, this method disables the middleware's cookie writing functionality to ensure the token is returned directly rather than set as a cookie.
getRefreshToken
public getRefreshToken(): ?ExpiringTokenReturns: Hazaar\Auth\ExpiringToken
create
Authorises the JWT token.
public create(string $identity, array $data): ExpiringTokenReturns: Hazaar\Auth\ExpiringToken
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | string | |
$data | array |
assumeIdentity
Establishes in-memory identity/data without generating or signing a token.
public assumeIdentity(string $identity, array $data): voidReturns: void
Equivalent to the first two lines of Hazaar\Auth\Session\Backend\JWT::create, but skips Hazaar\Auth\Session\Backend\JWT::getToken (and therefore Hazaar\Auth\Session\Backend\JWT::sign) entirely, so this works even when no private key is configured — e.g. a verify-only service that holds only a public key and never issues tokens itself.
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | string | |
$data | array |
load
Validates a JWT token.
public load(string $token, ?array $sessionData, string $tokenType = 'access', ?string $passphrase): boolReturns: bool
This method decodes the token, verifies its structure, and validates the signature using the configured public or private key. It supports RS, ES, and PS algorithms. It also checks standard claims like 'iss' (issuer) and 'exp' (expiration).
Parameters
| Parameter | Type | Description |
|---|---|---|
$token | string | the JWT token string to validate |
$sessionData | array | |
$tokenType | string | |
$passphrase | string |
refresh
Refreshes the session using the provided refresh token.
public refresh(string $token): boolReturns: bool
Unlike the access token, the refresh token is opaque, so this is a store lookup rather than a signature verification — see the class docblock. The store consumes the token as part of the lookup (single-use, rotated on every call to Hazaar\Auth\Session\Backend\JWT::getRefreshToken), so a token can never be redeemed twice.
Parameters
| Parameter | Type | Description |
|---|---|---|
$token | string | the refresh token to redeem |
revoke
Revokes a single refresh token outright (e.g. on logout), without rotating it.
public revoke(string $refreshToken): voidReturns: void
Parameters
| Parameter | Type | Description |
|---|---|---|
$refreshToken | string |
listDevices
Lists every outstanding device/session for an identity.
public listDevices(string $identity): arrayReturns: array
A no-op that returns an empty array if the configured refresh token store doesn't implement Hazaar\Auth\Interface\DeviceAwareRefreshTokenStore.
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | string |
revokeDevice
Revokes a single device/session outright (e.g. "log out this device").
public revokeDevice(string $identity, string $sessionId): voidReturns: void
A no-op if the configured refresh token store doesn't implement Hazaar\Auth\Interface\DeviceAwareRefreshTokenStore.
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | string | |
$sessionId | string |
revokeAll
Revokes every outstanding refresh token for an identity (e.g. on password change).
public revokeAll(string $identity): voidReturns: void
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | string |
getIdentity
Retrieves the identity associated with the current session.
public getIdentity(): ?stringReturns: string
resolveRefreshTokenStore
Resolves (and caches) the refresh token store from the refresh_tokens/refresh_tokens_options
private resolveRefreshTokenStore(): RefreshTokenStoreReturns: Hazaar\Auth\Interface\RefreshTokenStore
config, accepting either a class name or an already-constructed instance — mirrors Hazaar\OAuth\Server's store resolution.
Deliberately not called from the constructor: an instance that never mints or redeems a refresh token (e.g. a verify-only resource server holding only a public key) must not need a working store/database connection just to be constructed.
loadCryptoKey
Loads a cryptographic key from configuration or file.
private loadCryptoKey(string $name, array $cacheList): ?stringReturns: string
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | the name of the key in the configuration |
$cacheList | array | reference to the cache list for loaded keys |
buildToken
Builds a JWT token with the given JWT body and passphrase.
private buildToken(array $JWTBody, ?string $passphrase): stringReturns: string
Parameters
| Parameter | Type | Description |
|---|---|---|
$JWTBody | array | the body of the JWT token |
$passphrase | string | The passphrase to sign the JWT token. Defaults to null. |
generateDeviceFingerprint
Generates a device fingerprint based on specified HTTP headers.
private generateDeviceFingerprint(string $passphrase): stringReturns: string
This method constructs a unique fingerprint for the client device by concatenating the values of specified HTTP headers (defined in the configuration under 'fingerprintKeys') and encoding the result in base64.
An absent 'fingerprintKeys' config already defaults to ['HTTP_USER_AGENT', 'HTTP_ACCEPT'] via the constructor's Arr::enhance() call. An explicitly empty array must stay empty here — it is how a consumer opts a token out of device binding entirely (e.g. a portable bearer token verified by a different process than minted it, as OAuth access tokens are) — so this must not re-coerce [] back to a default.
Parameters
| Parameter | Type | Description |
|---|---|---|
$passphrase | string |
getAlgoName
Parses the algorithm name and extracts the algorithm type and bit length.
private getAlgoName(string $alg, ?int $bits): ?stringReturns: string
This method validates the provided algorithm string against supported types (HS, RS, ES, PS) and bit lengths (256, 384, 512). If valid, it populates the reference variable $bits with the bit length and returns the algorithm prefix.
Parameters
| Parameter | Type | Description |
|---|---|---|
$alg | string | The algorithm string to parse (e.g., 'HS256', 'RS512'). |
$bits | int | [out] Reference variable to store the extracted bit length (256, 384, or 512) |
getAlgoConst
Retrieves the OpenSSL algorithm constant based on the specified number of bits.
private getAlgoConst(int $bits): intReturns: int
This method maps the bit length (256, 384, or 512) to the corresponding OpenSSL SHA algorithm constant.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bits | int | The number of bits for the algorithm (e.g., 256, 384, 512). |
sign
Signs the JWT token.
private sign(array $JWTHeader, array $JWTBody, ?string $passphrase): stringReturns: string
Parameters
| Parameter | Type | Description |
|---|---|---|
$JWTHeader | array | the header of the JWT token |
$JWTBody | array | the body of the JWT token |
$passphrase | string |
Generated by Hazaar API Doc Generator on Fri, 04 Sep 2026 23:32:17 +0000