PHP code example of lithemod / jwt

1. Go to this page and download the library: Download lithemod/jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lithemod / jwt example snippets


use Lithe\Auth\JWT;

// Route configuration with JWT
$app->get('/protected', new JWT('your-secret-key', 'HS256', 3600), function ($req, $res) {
    return $res->send('Access granted!');
});

$app->post('/login', function ($req, $res) {
    $user = ['id' => 1, 'role' => 'admin', 'email' => '[email protected]']; // Example user
    $token = (new JWT())->generateToken($user);
    return $res->send(['token' => $token]);
});

$app->get('/protected-route', new JWT(), function ($req, $res) {
    return $res->send('Access to protected route.');
});

$app->post('/logout', function ($req, $res) {
    $token = $req->header('Authorization');
    (new JWT())->revokeToken($token);
    return $res->send('Token revoked.');
});

$app->post('/refresh', function ($req, $res) {
    $token = $req->header('Authorization');
    $newToken = (new JWT())->refreshToken($token);
    return $res->send(['token' => $newToken]);
});

$app->get('/user', new JWT(), function ($req, $res) {
    return $res->send($req->user);
});

$app->post('/validate', function ($req, $res) {
    $token = $req->header('Authorization');
    $isValid = (new JWT())->validateToken($token);
    return $res->send(['valid' => $isValid]);
});