PHP code example of flytachi / jwt

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

    

flytachi / jwt example snippets


use Flytachi\Jwt\JWT;
use Flytachi\Jwt\Entity\JwtPayload;
use Flytachi\Jwt\Entity\PrivateKey;
use Flytachi\Jwt\Entity\PublicKey;

$token = JWT::encode(
    new JwtPayload([
        'iss' => 'https://example.com',
        'sub' => 'user-12345',
        'aud' => 'https://api.example.com',
        'iat' => time(),
        'exp' => time() + 3600,
    ]),
    new PrivateKey('a-shared-secret', 'HS256'),
);

$payload = JWT::decode($token, [new PublicKey('a-shared-secret', 'HS256')]);
$userId  = $payload->getClaim('sub');

$token = JWT::encode(
    new JwtPayload(['sub' => 'user-12345']),
    new PrivateKey(openssl_pkey_get_private($pem), 'RS256', 'key-2024'),
);

$payload = JWT::decode($token, ['key-2024' => new PublicKey($publicKey, 'RS256')]);

$jwks = json_decode(file_get_contents('https://accounts.google.com/.well-known/jwks.json'), true);
$keys = JWK::parseKeySet($jwks);              // ['kid' => PublicKey, …]

$payload = JWT::decode($token, $keys);

JWT::decode($token, $keys, leeway: 30);       // tolerate 30s of clock skew

if ($payload->getClaim('iss') !== 'https://example.com') {
    throw new RuntimeException('Unexpected issuer.');
}