Firebase JWT (Stateless Auth)

The artiframe add jwt extension enables you to perform state-less API authorization in ArtiFrame projects using the industry standard firebase/php-jwt library. Created under src/Auth/JwtAuth.php, this service reduces Token Generation, Verification, Refresh operations, and HTTP request blocking (Bearer Token control) through middleware logic to a single line.

1. Installation and Configuration

Include the extension into your project via the terminal:

terminal
$ artiframe add jwt

After the command executes, the following settings will be appended to your .env file:

.env
JWT_SECRET_KEY=your_very_secret_and_long_key
JWT_ALGORITHM=HS256
JWT_EXPIRY=3600
Important: Before deploying to the Production environment, absolutely change the JWT_SECRET_KEY value to an unpredictable and long cryptographic string.
2. Generating Tokens (Login Process)

This is the generation process for the token you provide to the user upon logging in with their email and password (Access Token) and the token used to extend their session (Refresh Token).

AuthController.php
<?php
use Src\Auth\JwtAuth;

$jwt = new JwtAuth();

// After verifying the user's login credentials:
$payload = [
    'user_id' => 1453,
    'role'    => 'admin',
    'email'   => '[email protected]'
];

// Generate Access Token (Expiry equals JWT_EXPIRY in .env)
$accessToken = $jwt->generate($payload);

// Generate Refresh Token (Valid for 7 days, contains token_type = refresh claim)
$refreshToken = $jwt->generateRefreshToken(['user_id' => 1453]);

echo json_encode([
    'access_token'  => $accessToken,
    'refresh_token' => $refreshToken
]);
MethodParametersDescription
generate()array payload, int expiryReturns a Token by automatically injecting iat and exp (Expiration) values.
generateRefreshToken()array payload, int expiryReturns a token sealed with token_type: refresh and a default 7-day validity.
3. Protecting API Routes (Middleware)

When sending requests to your APIs from the Client (React/Vue/Mobile), they must send Authorization: Bearer <Token> in the HTTP Headers. You can catch and enforce this with a single function at the very top of your API method (or route).

UserController.php
<?php
use Src\Auth\JwtAuth;

// --- PROTECTED ZONE STARTS HERE ---
// If the token is missing, expired, or invalid, this line instantly returns a 401 Unauthorized and halts PHP with exit.
JwtAuth::middleware();

// If execution reaches here; the Token is SECURE.
// You can directly access the verified user's (payload) data from the $_REQUEST global.
$activeUser = $_REQUEST['jwt_user'];

echo "Welcome User ID: " . $activeUser['user_id'];
Middleware Power: This method saves you from the hassle of manually decoding tokens in every single file. If ArtiFrame's apiResponse() helper is defined, it will directly output the 401 response in an API-friendly format (JSON).
4. Manual Token Operations

Methods to use if you want to read the token, check its validity in the background, or merely decode a value (e.g., user_id) without throwing exceptions:

Verifying the Token
example.php
<?php
$response = $jwt->verify($token);

if ($response['status'] === 'success') {
    $payload = $response['data'];
} else {
    // Outputs error details (Token has expired, Invalid token signature etc.)
    echo $response['message'];
}
Reading Data Only (Force Decode)

Methods that yield the Payload without throwing an Exception (Error), even if the token has expired:

example.php
<?php
// Returns the payload as an array; returns null if it fails to decode.
$payload = $jwt->payload($token);

// Directly retrieves the user_id value from within the payload
$userId = $jwt->getUserId($token);

// Only checks if the token has expired
$isExpired = $jwt->isExpired($token);
5. Refreshing Tokens

Re-generates an expiring or expired token with identical data but a new validity duration (new exp).

example.php
<?php
// Send the old token, receive a brand new 3600-second token holding the same data
$newToken = $jwt->refresh($oldToken, 3600);