PHP code example of phithi92 / json-web-token

1. Go to this page and download the library: Download phithi92/json-web-token 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/ */

    

phithi92 / json-web-token example snippets


use Phithi92\JsonWebToken\Security\KeyManagement\JwtKeyManager;

$manager = new JwtKeyManager();

$manager->addKeyPair(
    private: file_get_contents('/path/private.pem'),
    public: file_get_contents('/path/public.pem'),
    kid: 'main-key'
);

$manager->addPassphrase(
    passphrase: getenv('JWT_KEY_PASSPHRASE'),
    kid: 'main-key'
);

// For symmetric algorithms (HS*, dir/A*GCM), register a shared secret
$manager->addPassphrase(
    passphrase: getenv('JWT_SHARED_SECRET'),
    kid: 'HS256'
);

use Phithi92\JsonWebToken\Token\JwtPayload;

$payload = (new JwtPayload())
    ->setIssuer('https://issuer.example')
    ->setAudience('https://service.example')
    ->setIssuedAt('now')
    ->setExpiration('+15 minutes')
    ->setJwtId('token-123')
    ->addClaim('role', 'admin');

$payload
    ->setClaimTimestamp('iat', time())
    ->setClaimTimestamp('exp', time() + 900);

use Phithi92\JsonWebToken\Token\Factory\JwtTokenServiceFactory;
use Phithi92\JsonWebToken\Token\Validator\JwtValidator;

$service   = JwtTokenServiceFactory::createDefault();
$validator = new JwtValidator();

$token = $service->createTokenString(
    algorithm: 'RS256',
    manager: $manager,
    payload: $payload,
    validator: $validator,
    kid: 'main-key'
);

$bundle = $service->createTokenFromArray(
    algorithm: 'RS256',
    manager: $manager,
    claims: ['iss' => 'https://issuer.example', 'exp' => time() + 900],
    validator: $validator,
    kid: 'main-key'
);

$bundle = $service->decryptToken(
    token: $token,
    manager: $manager,
    validator: $validator
);

$payload = $bundle->getPayload();

$isValid = $service->validateTokenClaims(
    bundle: $bundle,
    validator: $validator
);

use Phithi92\JsonWebToken\Token\Validator\InMemoryJwtIdValidator;
use Phithi92\JsonWebToken\Token\Validator\JwtValidator;

$jwtIdValidator = new InMemoryJwtIdValidator(
    allowList: ['token-123'],
    denyList: ['revoked-token'],
    useAllowList: true
);

$validator = new JwtValidator(
    expectedIssuer: 'https://issuer.example',
    expectedAudience: 'https://service.example',
    jwtIdValidator: $jwtIdValidator
);

$service->denyBundle($bundle, $validator);

$newBundle = $service->reissueBundle(
    interval: '+30 minutes',
    bundle: $bundle,
    manager: $manager,
    validator: $validator
);

use Phithi92\JsonWebToken\Exceptions\Token\InvalidTokenException;
use Phithi92\JsonWebToken\Exceptions\Token\MalformedTokenException;
use Phithi92\JsonWebToken\Exceptions\Token\UnsupportedTokenTypeException;
use Phithi92\JsonWebToken\Exceptions\Payload\ExpiredPayloadException;
use Phithi92\JsonWebToken\Exceptions\Payload\NotYetValidException;
use Phithi92\JsonWebToken\Exceptions\Payload\InvalidIssuerException;
use Phithi92\JsonWebToken\Exceptions\Payload\InvalidAudienceException;
use Phithi92\JsonWebToken\Exceptions\Crypto\SignatureVerificationException;
use Phithi92\JsonWebToken\Exceptions\Crypto\DecryptionException;
use Phithi92\JsonWebToken\Exceptions\Security\PassphraseNotFoundException;

try {
    $bundle = $service->decryptToken(
        token: $token,
        manager: $manager,
        validator: $validator
    );

    // Optional extra claim validation step
    $service->validateTokenClaims($bundle, $validator);

} catch (ExpiredPayloadException|NotYetValidException $e) {
    // 401: token is time-invalid (expired or not active yet)
} catch (InvalidIssuerException|InvalidAudienceException $e) {
    // 403: token is valid but not intended for this API/context
} catch (SignatureVerificationException|DecryptionException $e) {
    // 401: signature/JWE auth check failed
} catch (MalformedTokenException|InvalidTokenException|UnsupportedTokenTypeException $e) {
    // 400: structurally invalid or unsupported token
} catch (PassphraseNotFoundException $e) {
    // 500: server-side key configuration problem
}