PHP code example of swanflutter / native-jwt

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

    

swanflutter / native-jwt example snippets


use SwanFlutter\NativeJwt\JWT;
use SwanFlutter\NativeJwt\Key;

$secret = 'your-super-secret-key-of-at-least-32-bytes!!';

$payload = [
    'iss' => 'https://example.com',
    'sub' => 'user-123',
    'iat' => time(),
    'exp' => time() + 3600,
];

$token   = JWT::encode($payload, $secret, 'HS256');
$decoded = JWT::decode($token, new Key($secret, 'HS256'));

$privateKey = file_get_contents('private.pem');
$publicKey  = file_get_contents('public.pem');

$token   = JWT::encode($payload, $privateKey, 'RS256', 'my-key-id');
$decoded = JWT::decode($token, new Key($publicKey, 'RS256'));

// Same key format as RS* — just change the algorithm name.
$token   = JWT::encode($payload, $privateKey, 'PS256');
$decoded = JWT::decode($token, new Key($publicKey, 'PS256'));

// Keys are base64url-encoded raw bytes (compatible with sodium_crypto_sign_*).
$keyPair = sodium_crypto_sign_keypair();
$privKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
$pubKey  = base64_encode(sodium_crypto_sign_publickey($keyPair));

$token   = JWT::encode($payload, $privKey, 'EdDSA');
$decoded = JWT::decode($token, new Key($pubKey, 'EdDSA'));

$keys = [
    'key-2024' => new Key($publicKeyOld, 'RS256'),
    'key-2025' => new Key($publicKeyNew, 'RS256'),
];
$decoded = JWT::decode($token, $keys);

JWT::$leeway = 60; // tolerate up to 60 seconds of clock skew
$decoded = JWT::decode($token, new Key($publicKey, 'RS256'));

use SwanFlutter\NativeJwt\JWK;

// $jwks is the decoded JSON from a JWKS endpoint (e.g. Google, Firebase).
$keys = JWK::parseKeySet($jwks);           // returns array<kid, Key>
$decoded = JWT::decode($token, $keys);

use SwanFlutter\NativeJwt\CachedKeySet;

$keySet = new CachedKeySet(
    jwksUri:           'https://www.googleapis.com/oauth2/v3/certs',
    httpClient:        $psrHttpClient,      // PSR-18 ClientInterface
    requestFactory:    $psrRequestFactory,  // PSR-17 RequestFactoryInterface
    cache:             $psrCachePool,       // PSR-6 CacheItemPoolInterface
    expiresAfter:      3600,                // TTL in seconds (null = use Cache-Control)
    rateLimit:         true,                // max 10 refreshes/second
);

$decoded = JWT::decode($token, $keySet);

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use SwanFlutter\NativeJwt\CachedKeySet;

$keySet = new CachedKeySet(
    jwksUri:        'https://www.googleapis.com/oauth2/v3/certs',
    httpClient:     new Client(),
    requestFactory: new HttpFactory(),
    cache:          new FilesystemAdapter(),
    expiresAfter:   3600,
);

use SwanFlutter\NativeJwt\JWT;
use SwanFlutter\NativeJwt\Key;

$serviceAccount = json_decode(file_get_contents('service-account.json'), true);

$now = time();
$jwtPayload = [
    'iss'   => $serviceAccount['client_email'],
    'sub'   => $serviceAccount['client_email'],
    'aud'   => 'https://oauth2.googleapis.com/token',
    'iat'   => $now,
    'exp'   => $now + 3600,
    'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
];

$assertion = JWT::encode(
    $jwtPayload,
    $serviceAccount['private_key'],
    'RS256',
    $serviceAccount['private_key_id']
);

// Exchange the JWT assertion for an access token.
$response = (new GuzzleHttp\Client())->post('https://oauth2.googleapis.com/token', [
    'form_params' => [
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion'  => $assertion,
    ],
]);

$accessToken = json_decode((string) $response->getBody(), true)['access_token'];

use SwanFlutter\NativeJwt\Exceptions\JWTException;
use SwanFlutter\NativeJwt\Exceptions\ExpiredException;
use SwanFlutter\NativeJwt\Exceptions\SignatureInvalidException;

try {
    $decoded = JWT::decode($token, $keys);
} catch (ExpiredException $e) {
    // token has expired
} catch (SignatureInvalidException $e) {
    // signature verification failed
} catch (JWTException $e) {
    // all other JWT errors
}
bash
# EdDSA (Ed25519) support
# Linux: apt install php-sodium  |  macOS: brew install php
# Windows: enable extension=sodium in php.ini

# RSA JWK parsing (JWK::parseKeySet with RSA keys)
# Linux: apt install php-gmp  |  macOS: brew install php
# Windows: enable extension=gmp in php.ini

# CachedKeySet (remote JWKS fetch + PSR-6 cache)
composer