lcobucci/jwt
A lightweight, flexible JWT library for PHP. Create, sign, parse, and validate JSON Web Tokens with support for multiple algorithms, key types, constraints, and claims. Includes a fluent builder, token parser, and robust validation APIs.
Begin by installing via Composer: composer require lcobucci/jwt. The core workflow involves three steps: building tokens with Builder, signing them with a Signer (e.g., Hmac\Sha256 or Signer\RSA\Sha256), and validating using ValidationData and Constraints. For Laravel, integrate using a service provider or direct usage in auth-related services. Start by generating a minimal token:
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Token\Parsed;
$signer = new Sha256();
$key = 'your-secret-key';
$token = (new Builder())
->setIssuer('your-app')
->setAudience('your-client')
->setId('token-id-123', true)
->setIssuedAt(time())
->setExpiration(time() + 3600)
->set('uid', 42)
->sign($signer, $key)
->toString();
Parse and validate next:
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
$parser = new Parser();
$token = $parser->parse($tokenString);
// Validate standard claims (exp, iat, etc.) via ValidationData
$data = new ValidationData();
$data->setIssuer('your-app');
$data->setAudience('your-client');
$data->setId('token-id-123');
if ($token->validate($data)) {
// Validate against signer too
if ($token->verify($signer, $key)) {
$uid = $token->claims()->get('uid');
}
}
TokenIssuer class to centralize signing logic and key management. Inject Signer and configuration (keys, TTL).lcobucci/jwt’s Constraints (e.g., AllowedAudience, IssuedBy, SameDomainIssuedBy, NotBefore) with $token->assert($constraints) — more modern and composable than ValidationData.new Key('file:///path/to/key.pem').JWTAuthService with Builder/Parser usage. Use Token Retrieved events to hydrate user context. Store tokens in cache for revocation (use jti claim).RoleClaim::value) to prevent typos and improve maintainability.validate() only checks time-based and standard claims (exp, iat, nbf, iss, aud, jti). For issuer/audience, use ValidationData or pass constraints to assert().Signer instances are stateless and immutable; verify() and sign() accept both key strings or Key objects. Prefer Key for file-based keys to avoid accidental truncation.time() or Carbon::now()->timestamp). Avoid mktime() or strtotime() without explicit timezone.jti + Redis TTL or DB). Store jti + revoked timestamp on logout.Parser throws UnexpectedValueException on parse failures. Wrap parsing in try-catch and map to user-friendly messages. validate() and verify() return bool.Claim subclasses, but prefer built-in ones unless absolutely necessary. Builder accepts Claim objects for advanced claims (e.g., NonEmptyArrayClaim).How can I help you explore Laravel packages today?