PHP code example of omegaalfa / jwtoken

1. Go to this page and download the library: Download omegaalfa/jwtoken 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/ */

    

omegaalfa / jwtoken example snippets


 use Omegaalfa\Jwtoken\JwToken;

 $secret = getenv('JWT_SECRET');
 if ($secret === false) {
     throw new RuntimeException('JWT_SECRET must be configured');
 }

 $jwt = new JwToken($secret, 'HS256');
 $jwt->setExpectedIssuer('https://auth.example.com');
 $jwt->setExpectedAudience('example-api');
 $jwt->setClockSkew(30); // padrão: 10s, máximo: 60s

 $payload = [
     'sub' => 'user-123',
     'name' => 'Sophia',
     'email' => '[email protected]',
     'role' => 'editor',
     'iat' => time(),
     'exp' => time() + 900,
 ];

 $token = $jwt->createToken($payload);

 if ($jwt->validateToken($token)) {
     $claims = $jwt->decodeToken($token);
     printf("Token is valid for %s (%s)\n", $claims['name'], $claims['sub']);
 }
 

 try {
     $jwt->setExpectedIssuer('https://auth.example.com');
     $jwt->setExpectedAudience('example-api');
     $jwt->setClockSkew(60); // máximo permitido

     if (! $jwt->validateToken($tokenFromHeader)) {
         throw new RuntimeException('Token validation failed');
     }
 
     $user = $jwt->decodeToken($tokenFromHeader);
     // check custom claims before granting access
     if ($user['role'] !== 'admin') {
         throw new RuntimeException('insufficient role');
     }
 } catch (Exception $ex) {
     // map to HTTP 401/403 as needed
 }
 

 $jwt = new JwToken('current-secret', 'HS256');
 $jwt->setHmacKeys([
     'v1' => 'secret-legado',
     'v2' => 'secret-atual',
 ]);

 $token = $jwt->createToken($payload, 120, ['kid' => 'v2']);

 // Request validation automatically resolves `kid`
 $jwt->validateToken($token);
 

 // Using RS256
 $jwt = new JwToken(
     secretKey: 'unused-for-rs',
     algorithm: 'RS256',
     pathPrivateKey: __DIR__ . '/keys/private.pem',
     pathPublicKey: __DIR__ . '/keys/public.pem'
 );

 // Or using RS384 for higher security
 $jwt = new JwToken(
     secretKey: 'unused-for-rs',
     algorithm: 'RS384',
     pathPrivateKey: __DIR__ . '/keys/private.pem',
     pathPublicKey: __DIR__ . '/keys/public.pem'
 );

 // Or using RS512 for maximum security
 $jwt = new JwToken(
     secretKey: 'unused-for-rs',
     algorithm: 'RS512',
     pathPrivateKey: __DIR__ . '/keys/private.pem',
     pathPublicKey: __DIR__ . '/keys/public.pem'
 );

 $token = $jwt->createToken($payload);
 if ($jwt->validateToken($token)) {
     $claims = $jwt->decodeToken($token);
 }
 

 $jwt->setRsaKeyPaths(
     ['k1' => __DIR__ . '/keys/private_v1.pem', 'k2' => __DIR__ . '/keys/private_v2.pem'],
     ['k1' => __DIR__ . '/keys/public_v1.pem', 'k2' => __DIR__ . '/keys/public_v2.pem']
 );

 $jwt->createToken($payload, 300, ['kid' => 'k2']);
 $jwt->validateToken($token);
 

 class InMemoryRevocationStore implements RevocationStoreInterface
 {
     public function __construct(private array $revoked) {}

     public function isRevoked(string $jti): bool
     {
         return in_array($jti, $this->revoked, true);
     }
 }

 $jwt = new JwToken($secret);
 $jwt->revocationStore = new InMemoryRevocationStore(['compromised-jti']);
 

// Padrão é 10 segundos, máximo permitido é 60 segundos
$jwt->setClockSkew(30); // Recomendado para produção

// Example: Creating a token with iat validation
$payload = [
    'sub' => 'user-123',
    'iat' => time(), // Validated during createToken()
    'exp' => time() + 900,
];

$token = $jwt->createToken($payload);

use Omegaalfa\Jwtoken\JwToken;

$secret = getenv('JWT_SECRET');
if ($secret === false) {
    throw new RuntimeException('JWT_SECRET is not configured');
}

$jwt = new JwToken($secret, 'HS256');

$payload = [
    'sub' => 'user-123',
    'iss' => 'https://your-issuer.com',
    'aud' => 'your-api',
    'iat' => time(),
    'exp' => time() + 600, // 10 minutes
];

$token = $jwt->createToken($payload);

if ($jwt->validateToken($token)) {
    $decoded = $jwt->decodeToken($token);
    // use $decoded here
}

use Omegaalfa\Jwtoken\JwToken;

$secret = getenv('JWT_SECRET');
if ($secret === false) {
    throw new RuntimeException('JWT_SECRET is not configured');
}

$jwt = new JwToken($secret, 'HS256');

// Optional: validation policy
$jwt->expectedIssuer = 'https://your-issuer.com';
$jwt->expectedAudience = 'your-api';

$payload = [
    'sub' => 'user-123',
    'name' => 'John Doe',
    'email' => '[email protected]',
    'iss' => 'https://your-issuer.com',
    'aud' => 'your-api',
    'iat' => time(),
    'exp' => time() + 3600,
];

$token = $jwt->createToken($payload);

// Validation
if ($jwt->validateToken($token)) {
    $decoded = $jwt->decodeToken($token);
    print_r($decoded);
}

use Omegaalfa\Jwtoken\JwToken;

$fallbackSecret = getenv('JWT_SECRET'); // default secret

$jwt = new JwToken($fallbackSecret, 'HS256');

// Register multiple secrets identified by kid
$jwt->setHmacKeys([
    'v1' => 'old-secret',
    'v2' => 'current-secret',
]);

// When issuing new tokens, always use the kid of the current key
$payload = [
    'sub' => 'user-123',
    'iss' => 'https://your-issuer.com',
    'aud' => 'your-api',
];

$token = $jwt->createToken($payload, 60, ['kid' => 'v2']);

// On validation, the header is decoded, kid is read and the correct key is used automatically
$jwt->validateToken($token); // true if the signature is consistent

use Omegaalfa\Jwtoken\JwToken;

$jwt = new JwToken(
    secretKey: 'not used for RS256',
    algorithm: 'RS256',
    pathPrivateKey: __DIR__ . '/keys/private.pem',
    pathPublicKey: __DIR__ . '/keys/public.pem',
);

$payload = [
    'sub' => 'user-123',
    'iss' => 'https://your-issuer.com',
    'aud' => 'your-api',
];

$token = $jwt->createToken($payload);

if ($jwt->validateToken($token)) {
    $decoded = $jwt->decodeToken($token);
}

use Omegaalfa\Jwtoken\JwToken;

$jwt = new JwToken(
    secretKey: 'not used for RS256',
    algorithm: 'RS256',
    pathPrivateKey: __DIR__ . '/keys/private_default.pem',
    pathPublicKey: __DIR__ . '/keys/public_default.pem',
);

// Register specific paths for each kid
$jwt->setRsaKeyPaths(
    [
        'k1' => __DIR__ . '/keys/private_v1.pem',
        'k2' => __DIR__ . '/keys/private_v2.pem',
    ],
    [
        'k1' => __DIR__ . '/keys/public_v1.pem',
        'k2' => __DIR__ . '/keys/public_v2.pem',
    ],
);

$payload = [
    'sub' => 'user-123',
    'iss' => 'https://your-issuer.com',
    'aud' => 'your-api',
];

// Generate token signed with key pair v2
$token = $jwt->createToken($payload, 60, ['kid' => 'k2']);

// On validation, the header is read, kid is resolved and the correct public key is used
$jwt->validateToken($token); // true if the key pair and kid match

use Omegaalfa\Jwtoken\RevocationStoreInterface;
use Omegaalfa\Jwtoken\JwToken;

class InMemoryRevocationStore implements RevocationStoreInterface
{
    public function __construct(private array $revoked = []) {}

    public function isRevoked(string $jti): bool
    {
        return in_array($jti, $this->revoked, true);
    }
}

$jwt = new JwToken('secret_key');
$jwt->revocationStore = new InMemoryRevocationStore(['compromised-jti']);

// ✅ v3.0 (correct):
$jwt->setExpectedIssuer('https://auth.example.com');
$jwt->setExpectedAudience('example-api');
$jwt->setClockSkew(30); // max 60s (was 300s in v2.x)