Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Jwt Laravel Package

firebase/php-jwt

Encode and decode JSON Web Tokens (JWT) in PHP per RFC 7519. Supports common signing algorithms, key handling, header access after verification, and clock-skew leeway. Install via Composer; optional sodium_compat for libsodium environments.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • JWT Standard Compliance: The package fully adheres to RFC 7519 (JWT spec) and supports RFC 7515 (JWT Security Considerations), making it a drop-in replacement for any Laravel-based authentication system requiring JWT (e.g., API tokens, OAuth flows, or stateless auth).
  • Algorithm Flexibility: Supports HS256/HS384/HS512 (symmetric), RS256/RS384/RS512 (asymmetric), ES256/ES384/ES512 (ECDSA), and EdDSA (via libsodium), aligning with modern security best practices (e.g., OAuth 2.0, OpenID Connect).
  • Key Management: Integrates with JWK (JSON Web Key) sets and CachedKeySet for dynamic key rotation (critical for production-grade APIs). Supports kid (key ID) claims for multi-key validation.
  • Laravel Synergy: Works seamlessly with Laravel’s authentication contracts (Illuminate\Contracts\Auth\Authenticatable) and guard systems, enabling JWT-based sessions or API tokens alongside traditional database auth.

Integration Feasibility

  • Minimal Boilerplate: Requires ~5 lines of code for basic encode/decode (vs. ~50+ for custom implementations). Laravel’s service container can auto-resolve dependencies (e.g., Key, CachedKeySet).
  • Middleware Integration: Can be wrapped in Laravel’s middleware (e.g., VerifyJWTToken) to validate incoming requests, replacing or augmenting Laravel’s built-in auth middleware.
  • Caching Layer: CachedKeySet leverages PSR-6 caches (e.g., Redis, file-based), which Laravel already supports via Illuminate\Cache.
  • Testing: Includes PHPUnit tests and mockable exceptions, easing CI/CD pipelines.

Technical Risk

Risk Area Mitigation Strategy
Algorithm Misuse Enforce whitelisted algorithms in config (e.g., HS256 only for internal APIs).
Key Management Use CachedKeySet with short TTLs (e.g., 5 mins) for key rotation.
Libsodium Dependency Fallback to paragonie/sodium_compat if native libsodium is unavailable.
Performance Benchmark HS256 vs. RS256 for latency-sensitive APIs (HS256 is faster but less secure).
Exception Handling Centralize JWT error responses (e.g., 401 Unauthorized for SignatureInvalidException).

Key Questions for TPM

  1. Security Requirements:
    • Are asymmetric algorithms (RS256/ES256) mandatory, or is HS256 sufficient for internal APIs?
    • Should JWKS endpoints be used for public-facing APIs (e.g., OAuth providers)?
  2. Key Rotation Strategy:
    • How often should keys rotate? Will CachedKeySet’s auto-refresh suffice, or is manual intervention needed?
  3. Performance Constraints:
    • Will JWT validation be a bottleneck? If so, consider pre-validating tokens in a queue (e.g., Laravel Queues).
  4. Audit Logging:
    • Should failed JWT decodes (e.g., ExpiredException) trigger security alerts?
  5. Laravel Ecosystem:
    • Will this replace Laravel’s built-in Sanctum/Passport, or run alongside them?
    • Should JWT claims (e.g., sub, roles) map to Laravel’s user model or a custom structure?

Integration Approach

Stack Fit

  • Laravel Core: Integrates with:
    • Auth System: Extend Illuminate\Auth\Guard to validate JWTs.
    • Middleware: Create JwtMiddleware to parse tokens from Authorization: Bearer headers.
    • Service Container: Bind Firebase\JWT\JWT as a singleton for dependency injection.
  • Dependencies:
    • Required: firebase/php-jwt (JWT logic).
    • Optional:
      • paragonie/sodium_compat (if libsodium is missing).
      • guzzlehttp/guzzle + phpfastcache (for CachedKeySet).
      • league/oauth2-server (if integrating with OAuth 2.0).
  • Database: No direct DB dependency, but can store JWT blacklists (e.g., revoked tokens) in revoked_tokens table.

Migration Path

Phase Action Tools/Libraries
Evaluation Benchmark against Laravel Sanctum/Passport for performance/security tradeoffs. phpbench, laravel-debugbar
Pilot Replace a single API endpoint’s auth with JWT (e.g., /api/v1/protected). Laravel Middleware, Postman for testing
Core Integration Add JWT middleware globally; integrate with Laravel’s Auth::attempt() for hybrid auth. Illuminate\Auth\Events, HasApiTokens
Key Management Deploy CachedKeySet with Redis cache; set up key rotation cron job. spatie/laravel-cron-job
Monitoring Log JWT decode failures; alert on SignatureInvalidException spikes. Laravel Horizon, Sentry

Compatibility

  • Laravel Versions: Tested on Laravel 8+ (PHP 7.4+). For Laravel 7, ensure paragonie/sodium_compat is installed.
  • PHP Extensions:
    • Required: openssl (for RS/ES algorithms).
    • Optional: libsodium (for EdDSA; fallback to sodium_compat).
  • Existing Auth: Can coexist with Sanctum (session-based) or Passport (OAuth) via multi-guard configuration.

Sequencing

  1. Phase 1: Core JWT Support

    • Add firebase/php-jwt to composer.json.
    • Create JwtServiceProvider to bind the JWT class and configure defaults (e.g., JWT::$leeway = 300).
    • Implement JwtMiddleware to parse tokens from headers/cookies.
  2. Phase 2: Key Management

    • Set up CachedKeySet with Redis for JWKS caching.
    • Configure key rotation (e.g., weekly) via cron job.
  3. Phase 3: Laravel Integration

    • Extend Auth::user() to accept JWT payloads (e.g., sub claim maps to users(id)).
    • Add HasApiTokens trait to models for hybrid auth.
  4. Phase 4: Security Hardening

    • Restrict algorithms to HS256 or RS256 in config.
    • Implement rate limiting on JWT endpoints (e.g., throttle:60,1).

Operational Impact

Maintenance

  • Dependencies:
    • Critical: Monitor firebase/php-jwt for CVE updates (e.g., algorithm vulnerabilities).
    • Optional: paragonie/sodium_compat updates if using EdDSA.
  • Key Rotation:
    • Automate via CachedKeySet (refreshes on invalid key access).
    • Manual backup of private keys (e.g., RSA keys) in HSM or AWS KMS.
  • Logging:
    • Log JWT decode failures (e.g., SignatureInvalidException) to detect brute-force attacks.
    • Audit token issuance (e.g., iat, exp claims) for compliance.

Support

  • Common Issues:
    • Clock Skew: Set JWT::$leeway = 60 to account for server time differences.
    • Key Errors: Validate JWKS endpoints return valid JSON (e.g., {"keys": [...]}).
    • Algorithm Mismatch: Ensure kid claims match keys in CachedKeySet.
  • Debugging Tools:
    • Use jwt.io to decode tokens manually for troubleshooting.
    • Laravel’s dd() or Xdebug for payload inspection.
  • Documentation:
    • Maintain a runbook for:
      • Revoking compromised tokens (e.g., SQL DELETE FROM revoked_tokens).
      • Rotating keys without downtime.

Scaling

  • Performance:
    • HS256: ~1ms decode time (symmetric, fast).
    • RS256: ~5–10ms decode time (asymmetric, slower but more secure).
    • Caching: Cache decoded payloads in Redis for high-traffic APIs (e.g., `jwt:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata