- How do I install firebase/php-jwt in a Laravel project?
- Run `composer require firebase/php-jwt` to install the package. For environments without libsodium, add `paragonie/sodium_compat` via `composer require paragonie/sodium_compat`. No Laravel-specific setup is needed beyond Composer.
- Which Laravel versions does firebase/php-jwt support?
- The package works with Laravel 5.5+ and PHP 7.2+. For Laravel 10.x, it’s fully compatible with PHP 8.1+. Check the [GitHub actions](https://github.com/firebase/php-jwt/actions) for the latest test coverage.
- Can I use firebase/php-jwt with Laravel Sanctum or Passport?
- Yes. While Sanctum/Passport handle session-based auth, you can use firebase/php-jwt for stateless JWT validation in middleware or API gateways. Combine them by validating tokens in a custom middleware before Sanctum/Passport checks.
- How do I enforce strict JWT algorithm validation (e.g., reject 'none')?
- Use `new Key($key, 'HS256')` (or your preferred algorithm) during decode. To block weak algorithms globally, wrap `JWT::decode()` in middleware and throw an exception if the `alg` claim doesn’t match your allowed list.
- What’s the best way to handle key rotation for RS256 tokens?
- Use `CachedKeySet` with a short TTL (e.g., 5 minutes) to cache JWKS from a public endpoint. Invalidate the cache via webhooks when keys rotate. Store private keys securely in AWS KMS, HashiCorp Vault, or Laravel’s encrypted env files.
- How do I integrate firebase/php-jwt with Laravel’s auth system?
- Decode the JWT in middleware, then set the user via `auth()->setUser($decoded)`. Example: `auth()->loginUsingId($decoded->sub)` if your payload includes a user ID. This bridges JWT validation with Laravel’s auth contracts.
- What’s the performance impact of RS256 vs. HS256 in Laravel?
- HS256 is significantly faster (~10x) than RS256 due to symmetric key operations. For high-throughput APIs, use HS256 with a strong secret. Reserve RS256 for public-key scenarios where security outweighs performance.
- Can I customize JWT headers (e.g., add 'kid' for key identification)?
- Yes. Pass a `stdClass` as the third argument to `JWT::encode()` to set custom headers like `kid` or `alg`. Example: `$jwt = JWT::encode($payload, $key, 'HS256', $headers, ['kid' => 'primary-key']);`
- How do I handle clock skew for `iat`, `nbf`, or `exp` claims?
- Set a leeway in seconds via `JWT::$leeway = 60;` before decoding. This accounts for minor time differences between servers. Avoid excessive leeway (>5 minutes) to prevent replay attacks.
- Are there alternatives to firebase/php-jwt for Laravel JWT auth?
- Yes. For Laravel, consider `typhon/jwt-auth` (Laravel-specific) or `webtoken/jwt-framework` (PHP-focused). firebase/php-jwt is lighter and RFC-compliant but lacks Laravel’s built-in auth integration. Choose based on whether you need middleware hooks or JWKS caching.