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-opensslandext-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 withgetClaim().PrivateKey/PublicKey— key material bound to an algorithm.PrivateKeysigns;PublicKeyverifies.JWT— the façade with two static methods:encode()anddecode().JWK— a parser that turns a JSON Web Key Set into a map ofPublicKeyobjects, keyed bykid.
Key features
- All popular algorithms — HMAC (
HS256/384/512), RSA (RS256/384/512), and ECDSA (ES256/384/512). - Full JWKS support — parse
RSA,EC, andoctkeys straight from a provider’s/.well-known/jwks.json. - Time-claim validation —
exp,nbf, andiatare checked automatically, with a configurableleewayfor 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
JWTExceptionyou 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 parsingext-json— encoding and decoding token segments
Works on any OS, including Windows — there are no POSIX dependencies.
Install
composer require flytachi/jwtQuick start
Sign a payload with a shared secret, then verify it back:
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-42Walk through it end to end in the Quickstart.
Source & links
- GitHub — github.com/flytachi/php-jwt
- Packagist — packagist.org/packages/flytachi/jwt
Continue with Installation & requirements, the Quickstart, and the Mental model.