PHP code example of dev-toolbelt / jwt-token-manager

1. Go to this page and download the library: Download dev-toolbelt/jwt-token-manager 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/ */

    

dev-toolbelt / jwt-token-manager example snippets


use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;

// Create configuration
$config = new JwtConfig(
    privateKey: file_get_contents('/path/to/private.key'),
    publicKey: file_get_contents('/path/to/public.key'),
    issuer: 'https://api.yourapp.com'
);

// Initialize the manager
$manager = new JwtTokenManager($config);

// Generate a token
$token = $manager->encode('user-123', [
    'name' => 'John Doe',
    'role' => 'admin'
]);

// Decode and validate the token
$payload = $manager->decode($token);

echo $payload->getSubject();      // "user-123"
echo $payload->getClaim('name');  // "John Doe"
echo $payload->getClaim('role');  // "admin"

use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\Enums\Security\Algorithm;
use DevToolbelt\Enums\Locale\Timezone;

$config = new JwtConfig(
    privateKey: $privateKey,
    publicKey: $publicKey,
    issuer: 'https://api.yourapp.com',
    algorithm: Algorithm::RS256,        // Default: RS256
    ttlMinutes: 60,                     // Default: 60 (1 hour)
    refreshTtlMinutes: 20160,           // Default: 20160 (14 days)
    audience: ['https://app.yourapp.com'],
    

// From key files
$config = JwtConfig::fromKeyFiles(
    privateKeyPath: '/path/to/private.key',
    publicKeyPath: '/path/to/public.key',
    issuer: 'https://api.yourapp.com'
);

// From array (useful for framework config files)
$config = JwtConfig::fromArray([
    'private_key' => $privateKey,
    'public_key' => $publicKey,
    'issuer' => 'https://api.yourapp.com',
    'algorithm' => 'RS256',
    'ttl_minutes' => 60,
    'audience' => ['https://app.yourapp.com'],
    'timezone' => 'America/Sao_Paulo'  // Or use Timezone enum
]);

use DevToolbelt\Enums\Security\Algorithm;

// Check algorithm properties
Algorithm::RS256->isAsymmetric();  // true
Algorithm::HS256->isSymmetric();   // true
Algorithm::RS256->isRSA();         // true
Algorithm::ES256->isECDSA();       // true

use DevToolbelt\Enums\Locale\Timezone;

// Using the enum directly
$config = new JwtConfig(
    privateKey: $privateKey,
    publicKey: $publicKey,
    issuer: 'https://api.yourapp.com',
    timezone: Timezone::AMERICA_SAO_PAULO
);

// Available timezone helper methods
Timezone::AMERICA_NEW_YORK->toDateTimeZone();    // Returns DateTimeZone instance
Timezone::EUROPE_LONDON->getUtcOffset();         // Returns offset in seconds
Timezone::ASIA_TOKYO->getUtcOffsetString();      // Returns "+09:00"

// Create from string (useful for config files)
$timezone = Timezone::from('America/Sao_Paulo');
$timezone = Timezone::tryFrom('Invalid/Zone');   // Returns null for invalid zones

$manager = new JwtTokenManager($config);

// Simple token with just a subject
$token = $manager->encode('user-123');

// Token with custom claims
$token = $manager->encode('user-123', [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'roles' => ['admin', 'editor'],
    'tenant_id' => 'tenant-456'
]);

// Get the generated session ID and JWT ID
$sessionId = $manager->getLastSessionId();  // UUID v7
$jti = $manager->getLastJti();              // UUID v7

try {
    $payload = $manager->decode($token);

    // Standard claim accessors
    $payload->getSubject();      // sub claim
    $payload->getIssuer();       // iss claim
    $payload->getAudience();     // aud claim (array)
    $payload->getExpiration();   // exp claim (timestamp)
    $payload->getIssuedAt();     // iat claim (timestamp)
    $payload->getNotBefore();    // nbf claim (timestamp)
    $payload->getJti();          // jti claim
    $payload->getSessionId();    // sid claim
    $payload->getType();         // typ claim

    // Custom claims
    $payload->getClaim('role');  // Get any custom claim
    $payload->hasClaim('role');  // Check if claim exists

    // Get all claims as array
    $allClaims = $payload->toArray();

    // Check expiration
    if ($payload->isExpired()) {
        // Token has expired
    }

} catch (ExpiredTokenException $e) {
    // Token has expired
} catch (InvalidSignatureException $e) {
    // Public key could not validate the token signature
} catch (InvalidTokenException $e) {
    // Token is malformed or not yet valid
} catch (InvalidClaimException $e) {
    // A claim validation failed
    $e->getClaimName();      // Which claim failed
    $e->getActualValue();    // What value was received
    $e->getExpectedValue();  // What was expected
} catch (MissingClaimsException $e) {
    // Required claims are missing
    $e->getMissingClaims();  // Array of missing claim names
}

// Generate a refresh token
$refreshToken = $manager->generateRefreshToken();  // SHA1 hash

// Get TTL values
$accessTtl = $manager->getTokenTtl();        // In seconds
$refreshTtl = $manager->getRefreshTokenTtl(); // In seconds

// Override the token type for refresh tokens
$refreshToken = $manager->encode('user-123', [
    'typ' => 'refresh'
]);

// Override not-before time
$token = $manager->encode('user-123', [
    'nbf' => time() + 3600  // Token valid in 1 hour
]);

// Override audience for specific consumers
$token = $manager->encode('user-123', [
    'aud' => ['https://mobile-app.yourapp.com']
]);

// config/jwt.php
return [
    'private_key' => storage_path('keys/private.key'),
    'public_key' => storage_path('keys/public.key'),
    'issuer' => env('APP_URL'),
    'audience' => [env('FRONTEND_URL')],
    'ttl_minutes' => 60,
];

// app/Providers/AppServiceProvider.php
use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;

public function register(): void
{
    $this->app->singleton(JwtTokenManager::class, function ($app) {
        $config = JwtConfig::fromKeyFiles(
            privateKeyPath: config('jwt.private_key'),
            publicKeyPath: config('jwt.public_key'),
            issuer: config('jwt.issuer'),
            audience: config('jwt.audience'),
            ttlMinutes: config('jwt.ttl_minutes')
        );

        return new JwtTokenManager($config);
    });
}

// Usage in a controller or service
use DevToolbelt\JwtTokenManager\JwtTokenManager;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        // Using dependency injection
        $manager = app(JwtTokenManager::class);

        // Or using the helper with type hint
        /** @var JwtTokenManager $manager */
        $manager = app()->make(JwtTokenManager::class);

        $token = $manager->encode($user->id, [
            'name' => $user->name,
            'email' => $user->email
        ]);

        return response()->json(['token' => $token]);
    }
}

// src/Controller/AuthController.php
namespace App\Controller;

use DevToolbelt\JwtTokenManager\JwtTokenManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class AuthController extends AbstractController
{
    public function __construct(
        private readonly JwtTokenManager $jwtManager
    ) {}

    #[Route('/api/login', name: 'api_login', methods: ['POST'])]
    public function login(): JsonResponse
    {
        $user = $this->getUser();

        $token = $this->jwtManager->encode($user->getId(), [
            'email' => $user->getEmail(),
            'roles' => $user->getRoles()
        ]);

        return $this->json(['token' => $token]);
    }
}

// config/container.php
use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;
use Psr\Container\ContainerInterface;

return [
    JwtTokenManager::class => function (ContainerInterface $c) {
        $config = JwtConfig::fromKeyFiles(
            privateKeyPath: __DIR__ . '/../keys/private.key',
            publicKeyPath: __DIR__ . '/../keys/public.key',
            issuer: $_ENV['APP_URL']
        );

        return new JwtTokenManager($config);
    },
];

// src/Action/LoginAction.php
use DevToolbelt\JwtTokenManager\JwtTokenManager;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class LoginAction
{
    public function __construct(
        private readonly JwtTokenManager $jwtManager
    ) {}

    public function __invoke(Request $request, Response $response): Response
    {
        $data = $request->getParsedBody();

        // After validating credentials...
        $token = $this->jwtManager->encode($userId, [
            'email' => $data['email']
        ]);

        $response->getBody()->write(json_encode(['token' => $token]));
        return $response->withHeader('Content-Type', 'application/json');
    }
}

// app/Config/Services.php
namespace Config;

use CodeIgniter\Config\BaseService;
use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;

class Services extends BaseService
{
    public static function jwtManager(bool $getShared = true): JwtTokenManager
    {
        if ($getShared) {
            return static::getSharedInstance('jwtManager');
        }

        $config = JwtConfig::fromKeyFiles(
            privateKeyPath: WRITEPATH . 'keys/private.key',
            publicKeyPath: WRITEPATH . 'keys/public.key',
            issuer: base_url()
        );

        return new JwtTokenManager($config);
    }
}

// app/Controllers/Auth.php
namespace App\Controllers;

use Config\Services;

class Auth extends BaseController
{
    public function login()
    {
        $manager = Services::jwtManager();

        // After validating credentials...
        $token = $manager->encode($user->id, [
            'email' => $user->email,
            'name' => $user->name
        ]);

        return $this->response->setJSON(['token' => $token]);
    }
}

// config/services.php
use Cake\Core\Container;
use Cake\Core\ServiceProvider;
use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;

class JwtServiceProvider extends ServiceProvider
{
    protected array $provides = [JwtTokenManager::class];

    public function services(Container $container): void
    {
        $container->addShared(JwtTokenManager::class, function () {
            $config = JwtConfig::fromKeyFiles(
                privateKeyPath: CONFIG . 'keys/private.key',
                publicKeyPath: CONFIG . 'keys/public.key',
                issuer: env('APP_URL', 'https://localhost')
            );

            return new JwtTokenManager($config);
        });
    }
}

// In src/Application.php, register the provider:
// $container->addServiceProvider(new JwtServiceProvider());

// src/Controller/AuthController.php
namespace App\Controller;

use DevToolbelt\JwtTokenManager\JwtTokenManager;

class AuthController extends AppController
{
    public function login()
    {
        $manager = $this->getContainer()->get(JwtTokenManager::class);

        // After validating credentials...
        $token = $manager->encode($user->id, [
            'email' => $user->email
        ]);

        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode(['token' => $token]));
    }
}

// config/web.php
return [
    'components' => [
        'jwt' => [
            'class' => 'app\components\JwtComponent',
        ],
    ],
];

// components/JwtComponent.php
namespace app\components;

use DevToolbelt\JwtTokenManager\JwtConfig;
use DevToolbelt\JwtTokenManager\JwtTokenManager;
use yii\base\Component;

class JwtComponent extends Component
{
    private ?JwtTokenManager $manager = null;

    public function init(): void
    {
        parent::init();

        $config = JwtConfig::fromKeyFiles(
            privateKeyPath: \Yii::getAlias('@app/config/keys/private.key'),
            publicKeyPath: \Yii::getAlias('@app/config/keys/public.key'),
            issuer: \Yii::$app->params['appUrl']
        );

        $this->manager = new JwtTokenManager($config);
    }

    public function getManager(): JwtTokenManager
    {
        return $this->manager;
    }
}

// controllers/AuthController.php
namespace app\controllers;

use yii\rest\Controller;

class AuthController extends Controller
{
    public function actionLogin()
    {
        $manager = \Yii::$app->jwt->getManager();

        // After validating credentials...
        $token = $manager->encode($user->id, [
            'email' => $user->email,
            'name' => $user->name
        ]);

        return ['token' => $token];
    }
}