Pular para o conteúdo principal

JWT Wrapper

Create and validate JWT tokens in a few lines, with the same API for a shared secret or a key pair, and no weak keys accepted.

Sponsor Build Status Opensource ByJG Install MCP Server GitHub source GitHub license GitHub release

Why​

Signing a token is easy; getting the details right is not. Claims like iat, exp and nbf have to be set and checked, the token has to be read from the Authorization header, and a short HMAC secret silently makes every token easy to forge.

JWT Wrapper takes care of them:

$jwt = new JwtWrapper('example.com', new JwtHashHmacSecret(getenv('JWT_SECRET')));

$token = $jwt->generateToken($jwt->createJwtData(['userId' => 123], 3600));
$data = $jwt->extractData(); // reads "Authorization: Bearer ..." and validates it
  • One API, two kinds of keys. Swap JwtHashHmacSecret for JwtOpenSSLKey (RSA or ECDSA) and nothing else changes.
  • No weak secrets. An HMAC secret shorter than the algorithm needs is refused, and generateSecret() creates a proper one.

Features​

  • Simple API: Create and validate JWT tokens with minimal code
  • Flexible Signing: Support for both HMAC (shared secret) and RSA/ECDSA (public/private key) methods
  • Automatic Claims: Built-in handling of standard JWT claims (iat, exp, nbf)
  • HTTP Integration: Helper methods for extracting tokens from HTTP headers
  • Key Management: Intuitive interfaces for different key types

Installation​

composer require "byjg/jwt-wrapper"

Quick Example​

The HMAC secret must be base64 encoded and decode to at least 64 bytes for the default HS512 algorithm (32 for HS256, 48 for HS384); a shorter key fails with Provided key is too short. See Key Types.

// Create a JWT token using HMAC
$server = "example.com";
// Base64 of at least 64 random bytes, created once with JwtWrapper::generateSecret(64)
$secret = new \ByJG\JwtWrapper\JwtHashHmacSecret(getenv("JWT_SECRET"));
$jwtWrapper = new \ByJG\JwtWrapper\JwtWrapper($server, $secret);

// Add custom data and set expiration
$token = $jwtWrapper->generateToken(
$jwtWrapper->createJwtData(["userId" => 123], 3600)
);

// Validate and extract data
try {
$jwtData = $jwtWrapper->extractData($token);
$userId = $jwtData->data->userId;
} catch (\UnexpectedValueException | \ByJG\JwtWrapper\JwtWrapperException $e) {
// Handle invalid, expired or tampered token
}

Documentation​

Detailed documentation:

DocumentDescription
OverviewIntroduction and core concepts
Key TypesHMAC and OpenSSL key configuration
Creating TokensToken generation and customization
Validating TokensToken validation and data extraction
API ReferenceComplete class and method documentation

Examples​

The library includes complete examples in the example directory showing:

  • Token creation with login.php
  • Token validation with api.php
  • Client-side usage with client.html

Running Tests​

vendor/bin/phpunit

Open source ByJG