Package · jwt

JWT

Flytachi JWT is a modern, security-first library for encoding and decoding JSON Web Tokens in PHP. It leans on strict typing and value objects to make misuse hard, supports every popular signing algorithm, and ships a built-in JWKS parser so you can verify tokens from Google, Apple, Auth0, and friends without extra dependencies.

Philosophy

  • Security-first — signatures are compared with hash_equals (constant-time, timing-attack resistant), and the verifying key’s algorithm must match the token’s header, which closes the classic algorithm-confusion attack.
  • Strictly typed — keys, headers, and payloads are value objects (PrivateKey, PublicKey, JwtPayload), not loose strings and arrays. You can’t accidentally pass an HMAC secret where a public key belongs.
  • Zero heavy dependencies — only ext-openssl and ext-json. The JWKS-to-PEM conversion is done in pure PHP via hand-rolled ASN.1 encoding.

Core concepts

  • JwtPayload — the claims of a token (sub, exp, custom fields). A value object you read with getClaim().
  • PrivateKey / PublicKey — key material bound to an algorithm. PrivateKey signs; PublicKey verifies.
  • JWT — the façade with two static methods: encode() and decode().
  • JWK — a parser that turns a JSON Web Key Set into a map of PublicKey objects, keyed by kid.

Key features

  • All popular algorithms — HMAC (HS256/384/512), RSA (RS256/384/512), and ECDSA (ES256/384/512).
  • Full JWKS support — parse RSA, EC, and oct keys straight from a provider’s /.well-known/jwks.json.
  • Time-claim validationexp, nbf, and iat are checked automatically, with a configurable leeway for clock skew.
  • Key rotation via kid — asymmetric tokens carry a Key ID; decode() picks the right key from the set for you.
  • Robust errors — every failure throws a single JWTException you can catch.

Good fit for

Stateless authentication, API access tokens, verifying third-party ID tokens (OIDC / OAuth2), and any place you need a signed, tamper-evident claim you can validate without a shared session store.

Requirements

  • PHP ≥ 8.1
  • ext-openssl — signing and verifying RSA/ECDSA, and JWKS key parsing
  • ext-json — encoding and decoding token segments

Works on any OS, including Windows — there are no POSIX dependencies.

Install

bash
composer require flytachi/jwt

Quick start

Sign a payload with a shared secret, then verify it back:

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

$token = JWT::encode(
  new JwtPayload(['sub' => 'user-42', 'exp' => time() + 3600]),
  new PrivateKey('my-secret', 'HS256')
);

$payload = JWT::decode($token, [new PublicKey('my-secret', 'HS256')]);
echo $payload->getClaim('sub'); // user-42

Walk through it end to end in the Quickstart.

Continue with Installation & requirements, the Quickstart, and the Mental model.