Path in the Gestor bibliotecas/jwt.php
Generates and validates HS256 JWTs with a set of symmetric keys stored in the database, with rotation and a grace period.
Keys
The set is stored as JSON in the variaveis table (modulo='sistema', id='jwt_keys'), each key with key_id, key_secret (256 bits), created_at, status (active/expired) and expired_at. The first call to jwt_generate_token() creates the active key if there is none.
jwt_rotate_keys() expires the active key, creates a new one and deletes the expired ones whose grace period is over. The grace period is AUTH_JWT_GRACE_HOURS (default 24) hours counted from expired_at.
Usage
gestor_incluir_biblioteca('jwt');
$token = jwt_generate_token(['sub' => $userId, 'exp' => time() + 3600]);
try {
$r = jwt_validate_token($token); // ['status' => 'Active'|'Grace', 'payload' => [...]]
if (($r['payload']['exp'] ?? 0) < time()) throw new Exception('Expired token.');
if ($r['status'] === 'Grace') { /* issue a new token */ }
} catch (Exception $e) {
// malformed, unknown kid, invalid signature or key outside the grace period
}Other details:
-
iatis added when missing; the header carrieskidwith thekey_id. -
The header's
algis ignored (verification is always HMAC-SHA256), which prevents algorithm-confusion attacks. -
The secret keys are stored in plain text in the
variaveistable: anyone who can read the database (or a backup) can issue tokens.
Internal helpers (used by the functions above; rarely called directly): jwt_base64url_encode(), jwt_base64url_decode(), jwt_rotation_days(), jwt_grace_hours(), jwt_keys_load(), jwt_keys_save(), jwt_nova_chave(), jwt_get_active_key().
Functions
Generated from gestor/bibliotecas/jwt.php · 11 functions
jwt_base64url_encode
view source · line 28 ↗jwt_base64url_encode($data)Parameters
$data
jwt_base64url_decode
view source · line 32 ↗jwt_base64url_decode($data)Parameters
$data
jwt_rotation_days
view source · line 40 ↗jwt_rotation_days()jwt_grace_hours
view source · line 44 ↗jwt_grace_hours()jwt_keys_load
view source · line 55 ↗jwt_keys_load(): arrayCarrega o conjunto de chaves JWT do banco.
Returns
jwt_keys_save
view source · line 78 ↗jwt_keys_save(array $keys): voidPersiste o conjunto de chaves JWT no banco (insert ou update).
Parameters
$keysarray- Lista de chaves.
Returns
jwt_nova_chave
view source · line 106 ↗jwt_nova_chave(string $status = 'active'): arrayCria uma nova estrutura de chave JWT.
Parameters
$statusstring- 'active' ou 'expired'.
Returns
jwt_get_active_key
view source · line 120 ↗jwt_get_active_key(): arrayObtém a chave ativa; cria uma se ainda não existir.
Returns
jwt_generate_token
view source · line 142 ↗jwt_generate_token(array $payload): stringGera um token JWT assinado com a chave ativa.
Parameters
$payloadarray- Reivindicações do token.
Returns
jwt_validate_token
view source · line 169 ↗jwt_validate_token(string $token): arrayValida um token JWT.
Parameters
$tokenstring- Token JWT.
Returns
jwt_rotate_keys
view source · line 216 ↗jwt_rotate_keys(): arrayRotaciona as chaves JWT: marca a ativa como expirada, gera uma nova ativa e purga as chaves expiradas que já ultrapassaram o período de carência.
Returns