Search by

gadwinn / jwt

Gadwinn

A lightweight, framework-agnostic JWT library for signing, verifying and validating JSON Web Tokens.

Package info

github.com/Gadwinn/jwt

pkg:composer/gadwinn/jwt

Statistics

Installs: 1

Dependents: 0

Suggesters: 2

Stars: 0

Open Issues: 0

v0.1.0 2026-11-17 15:00 UTC

This package is auto-updated.

Last update: 2026-11-18 11:17:28 UTC


README

A lightweight, framework-agnostic JWT library for signing, verifying and validating JSON Web Tokens — built on a static facade with swappable, PSR-friendly collaborators.

Tech Stack

  • PHP >= 8.3 (readonly classes, enums, intersection types)
  • ext-openssl — RSA signing/verification
  • ext-sodium — EdDSA (Ed25519) signing/verification
  • psr/clock ^1.0 — time source for claim validation (PSR-20)
  • psr/simple-cache ^3.0 — JWKS caching (PSR-16)
  • ext-curl (suggested) — required only for the default remote JWKS HTTP client

Supported algorithms

Family Algorithms Key material
HMAC HS256 HS384 HS512 shared secret string
RSA RS256 RS384 RS512 PEM public key (+ PEM private to sign)
EdDSA EdDSA (Ed25519) raw/PEM key pair

PS*, ES* and none are defined in the Algorithm enum but intentionally not accepted by the signer/verifier. none is always rejected.

Installation

composer require gadwinn/jwt

Usage

All operations go through the static G\Jwt\Jwt facade. Keys are passed as immutable G\Jwt\ValueObject\Key value objects; algorithms as the G\Jwt\Enum\Algorithm enum.

HMAC — sign & verify (shared secret)

use G\Jwt\Jwt;
use G\Jwt\Enum\Algorithm;
use G\Jwt\ValueObject\Key;

$key = new Key('a-very-long-shared-secret');

$jwt = Jwt::encode(
    payload: ['sub' => '42', 'iat' => time(), 'exp' => time() + 3600],
    key: $key,
    algorithm: Algorithm::HS256,
);

// Verify the signature against the algorithm you expect.
// Returns a decoded Token.
$token = Jwt::verify($jwt, $key, expected: Algorithm::HS256);

$token->getClaim('sub');        // '42'
$token->getAlgorithm();         // Algorithm::HS256

The expected algorithm is mandatory: give it with expected: or bind it to the key (new Key($secret, algorithm: Algorithm::HS256)). verify() throws when neither is present, because the algorithm announced by the token itself is never trusted. In addition, none is always rejected, a PEM key is refused as an HMAC secret (the classic RSA-public-key-as-secret forgery), and so is an empty secret.

RSA — asymmetric sign & verify

The private key signs; the public key verifies. Both are PEM strings carried by the same Key API.

use G\Jwt\Jwt;
use G\Jwt\Enum\Algorithm;
use G\Jwt\ValueObject\Key;

$privatePem = file_get_contents('/path/to/private.pem');
$publicPem  = file_get_contents('/path/to/public.pem');

// material = public PEM, private = PEM private key
$signingKey = new Key(material: $publicPem, private: $privatePem);

$jwt = Jwt::encode(
    payload: ['sub' => 'service-a', 'exp' => time() + 600],
    key: $signingKey,
    algorithm: Algorithm::RS256,
);

// Verifiers only need the public key.
$token = Jwt::verify($jwt, new Key($publicPem), expected: Algorithm::RS256);

EdDSA (Ed25519)

use G\Jwt\Jwt;
use G\Jwt\Enum\Algorithm;
use G\Jwt\ValueObject\Key;

$keyPair    = sodium_crypto_sign_keypair();
$privateKey = sodium_crypto_sign_secretkey($keyPair);
$publicKey  = sodium_crypto_sign_publickey($keyPair);

$jwt   = Jwt::encode(['sub' => '42'], new Key($publicKey, $privateKey), Algorithm::EdDSA);
$token = Jwt::verify($jwt, new Key($publicKey), Algorithm::EdDSA);

Custom headers

The typ and alg headers are managed for you; any extra header (e.g. kid) is merged in:

$jwt = Jwt::encode(
    payload: ['sub' => '42'],
    key: $signingKey,
    algorithm: Algorithm::RS256,
    header: ['kid' => '2024-rotation-key'],
);

Decode without verifying

decode() parses the compact token into a Token without checking the signature — use it only for inspection (e.g. to read the kid before key resolution), never to trust claims.

$token = Jwt::decode($jwt);

$token->getKeyId();                  // 'kid' header, or null
$token->getHeaderValue('alg');
$token->getClaim('sub', 'anonymous'); // claim with default
$token->hasClaim('exp');             // bool

Validating claims

verify() only checks the signature. Registered-claim validation (RFC 7519 §4.1) is a separate, explicit step via the fluent validator — only the constraints you enable are enforced, and an enabled constraint whose claim is missing fails. A token is refused from the very second of its exp (RFC 7519).

use G\Jwt\Exception\ClaimValidationException;

$token = Jwt::verify($jwt, $key, Algorithm::HS256);

try {
    Jwt::validator()
        ->requireExpiration(leewaySeconds: 30)   // exp, with clock skew tolerance
        ->requireNotBefore()                      // nbf
        ->requireIssuedAt()                       // iat not in the future
        ->requireIssuer('https://issuer.example.com')
        ->requireAudience('https://api.example.com')
        ->requireSubject('42')
        ->requireJwtId('unique-token-id')
        ->validate($token);
} catch (ClaimValidationException $e) {
    // e.g. token expired, audience mismatch, missing required claim…
}

Deterministic time in tests (PSR-20)

Inject any Psr\Clock\ClockInterface to control "now" — ideal for testing expiry/nbf logic without sleeping.

use Psr\Clock\ClockInterface;

$frozenClock = new class implements ClockInterface {
    public function now(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('2026-01-01T00:00:00+00:00');
    }
};

Jwt::validator($frozenClock)
    ->requireExpiration()
    ->validate($token);

Verifying against a remote JWKS endpoint

JwksClient fetches a JWK Set over HTTP, resolves the right key by the token's kid, and converts it into a verification Key. Pass a PSR-16 cache to avoid a network round-trip on every verification; when a kid is absent from the cached set, the cache is busted once to transparently pick up rotated keys.

use G\Jwt\Jwt;
use G\Jwt\Enum\Algorithm;
use G\Jwt\Jwks\JwksClient;

// $cache is any Psr\SimpleCache\CacheInterface implementation.
$jwks = new JwksClient(cache: $cache, ttl: 3600);

$token = Jwt::decode($incomingJwt);                       // read headers (kid)
$key   = $jwks->resolveKey('https://issuer.example.com/.well-known/jwks.json', $token);

$verified = Jwt::verify($incomingJwt, $key, expected: Algorithm::RS256);

Jwt::validator()
    ->requireExpiration()
    ->requireIssuer('https://issuer.example.com')
    ->validate($verified);

A key resolved from a JWKS carries the algorithm declared by the issuer (alg), which verify() enforces. Unknown kid values trigger at most one forced refresh per minute, so forged tokens cannot make every verification download the key set. The default HTTP client only follows http/https URLs.

JwksClient is fully constructor-injectable for custom transports or DI:

use G\Jwt\Jwks\JwksClient;

$jwks = new JwksClient(
    http: $myHttpClient,        // G\Jwt\Contract\HttpClientInterface
    converter: $myConverter,    // G\Jwt\Contract\JwkConverterInterface
    cache: $cache,              // ?Psr\SimpleCache\CacheInterface
    ttl: 600,
);

Swapping collaborators (DI / testing)

The facade lazily builds default collaborators but lets you override them. Pass null to restore a default, or call Jwt::reset() to restore all of them.

Jwt::setEncoder($customEncoder);             // G\Jwt\Contract\EncoderInterface
Jwt::setDecoder($customDecoder);             // G\Jwt\Contract\DecoderInterface
Jwt::setSignerFactory($customSignerFactory); // G\Jwt\Contract\SignerFactoryInterface

Jwt::reset(); // back to defaults

Exceptions

All library exceptions extend G\Jwt\Exception\JwtException, so a single catch covers every failure mode:

Exception Raised when
SignatureVerificationException bad signature, malformed token, unsupported/none/mismatched alg
ClaimValidationException a required claim is missing, expired, not-yet-valid, or mismatched
KeyException invalid key material, missing JWK component, or kid not found
EncodingException invalid Base64url / JSON during encode or decode
TransportException JWKS HTTP request failed or returned a non-success status

License

MIT, see LICENSE.