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

Simplejwt Laravel Package

kelvinmo/simplejwt

SimpleJWT is a lightweight PHP 8+ library for JWT/JWS/JWE and JWK/COSE keys. Supports HS/RSA/ECDSA/EdDSA signatures, key management (RSA-OAEP, AES-KW, PBES2, ECDH-ES/X25519) and AES-GCM/CBC-HS encryption.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • RFC Compliance: Full support for JWT (RFC7519), JWS (RFC7515), JWE (RFC7516), and JWK (RFC7517), making it a robust choice for authentication/authorization in Laravel.
    • Algorithm Diversity: Supports HMAC, RSA, ECDSA, EdDSA, and advanced encryption schemes (AES-GCM, PBES2, ECDH-ES), aligning with modern security standards.
    • Key Management: Flexible key handling via JWK sets, PEM files, or direct secrets, reducing manual key management overhead.
    • Extensibility: Modular design (e.g., AlgorithmInterface, KeyInterface) allows custom algorithms or key types if needed.
    • Laravel Synergy: Integrates seamlessly with Laravel’s dependency injection (via Composer) and existing auth systems (e.g., Sanctum, Passport).
  • Gaps:

    • No Built-in Laravel Integration: Requires manual setup for Laravel-specific features (e.g., middleware, guards, or Sanctum/Passport hooks).
    • Key Rotation Complexity: Multi-key support exists, but Laravel’s caching layer (e.g., Redis) may need custom logic for dynamic key updates.
    • No Native Rate Limiting: JWT validation is stateless; rate limiting must be implemented separately (e.g., via middleware).

Integration Feasibility

  • Laravel Ecosystem:
    • Auth Guards: Can replace or augment Laravel’s default session-based auth with JWT (e.g., via HasApiTokens trait for Sanctum).
    • Middleware: Custom middleware for JWT validation (e.g., VerifyJWTToken) can integrate with Laravel’s pipeline.
    • Sanctum/Passport: Can serve as a backend for token generation/validation, though Passport’s OAuth2 features may require additional logic.
    • API Resources: JWT claims can be mapped to API resource fields (e.g., user roles) via Laravel’s Resource classes.
  • Database Impact:
    • Minimal; tokens are stateless. Claims can be stored in a personal_access_tokens table (Sanctum) or custom tables for revocation lists.
    • Revocation Strategy: Requires a custom table (e.g., revoked_tokens) with token hashes or IDs for blacklisting.

Technical Risk

  • High:
    • Key Management: Misconfigured keys (e.g., weak secrets, improper PEM formats) can lead to security vulnerabilities. Requires strict validation in Laravel’s config.
    • Algorithm Mismatches: Incorrect alg/enc headers (e.g., HS256 vs. RS256) can cause silent failures. Laravel’s validation layer must enforce consistency.
    • Performance: Large JWK sets or complex algorithms (e.g., RSA-OAEP) may impact response times. Benchmarking is critical for high-traffic APIs.
    • Dependency Risks: Relies on gmp, openssl, and sodium extensions. PHP environments (e.g., shared hosting) may lack these.
  • Medium:
    • Token Size: Large payloads (e.g., nested claims) may exceed HTTP limits. Compression or claim pruning may be needed.
    • Clock Skew: exp/nbf claims require synchronized server/client clocks. Laravel’s Carbon can help manage this.
  • Low:
    • Library Maturity: Actively maintained (PHP 8.5 compatible), with clear deprecation paths.

Key Questions

  1. Security:
    • How will key rotation be handled in production (e.g., rolling keys for short-lived tokens)?
    • Are there plans to integrate with Laravel Forge/Envoyer for secure key deployment?
  2. Performance:
    • What are the expected token sizes and validation latency under load?
    • Will JWE encryption add significant overhead for high-throughput APIs?
  3. Compliance:
    • Does the package support audit logging for JWT operations (e.g., token generation/validation)?
    • How will token revocation be enforced (e.g., short-lived tokens vs. blacklisting)?
  4. Laravel-Specific:
    • Should JWT validation be centralized in a base middleware or distributed per route?
    • How will JWT claims map to Laravel’s auth system (e.g., Auth::user() vs. decoded claims)?
  5. Monitoring:
    • Are there plans to add metrics (e.g., failed validations, algorithm usage) for observability?

Integration Approach

Stack Fit

  • Laravel Core:
    • Auth: Replace or extend Laravel’s Auth facade with JWT-based logic. Use HasApiTokens trait for Sanctum compatibility.
    • Middleware: Create a VerifyJWTToken middleware to validate tokens on API routes.
    • Guards: Extend TokenGuard to support JWT in Laravel’s auth system.
  • Dependencies:
    • Sanctum/Passport: Use simplejwt as the underlying token engine, but retain Sanctum’s token storage or Passport’s OAuth2 flows.
    • Redis: Cache JWK sets or revocation lists for performance.
    • Queue: Offload token validation for high-traffic APIs (e.g., using Laravel Queues).
  • Frontend:
    • JavaScript: Use libraries like jwt-decode for client-side claim extraction, with server-side validation.

Migration Path

  1. Phase 1: Pilot Integration
    • Replace a single API endpoint’s session auth with JWT (e.g., /api/auth/login).
    • Use simplejwt for token generation/validation, store tokens in Sanctum’s personal_access_tokens table.
    • Test with a small user group to validate performance and security.
  2. Phase 2: Full Auth Overhaul
    • Migrate all API routes to JWT validation via middleware.
    • Implement key rotation for production keys (e.g., monthly RSA key updates).
    • Add revocation logic (e.g., short-lived tokens or a revoked_tokens table).
  3. Phase 3: Advanced Features
    • Integrate JWE for encrypted payloads (e.g., PII in tokens).
    • Add custom claims (e.g., scope, aud) to align with OAuth2 or custom business logic.
    • Implement token introspection for debugging (e.g., /api/token/introspect).

Compatibility

  • Laravel Versions: Compatible with Laravel 9+ (PHP 8.0+). Test thoroughly with Laravel 10+.
  • Existing Auth: Can coexist with session auth but requires careful route guarding to avoid conflicts.
  • Third-Party Packages:
    • Sanctum: Replace Sanctum’s default token engine with simplejwt (minimal changes needed).
    • Passport: Use simplejwt for token generation but retain Passport’s authorization code flow.
    • Laravel Fortify: Customize Fortify’s CreateNewUser to emit JWTs instead of sessions.

Sequencing

  1. Setup:
    • Install kelvinmo/simplejwt via Composer.
    • Configure PHP extensions (gmp, openssl, sodium).
    • Generate and store keys (e.g., RSA private key in .env or AWS KMS).
  2. Development:
    • Create a JWTService class to wrap simplejwt logic (e.g., token generation, validation).
    • Build middleware (VerifyJWTToken) and guards (TokenGuard).
  3. Testing:
    • Unit tests for token generation/validation.
    • Integration tests with Laravel’s auth system.
    • Security tests (e.g., brute force, algorithm downgrade attacks).
  4. Deployment:
    • Roll out in stages (e.g., non-critical APIs first).
    • Monitor token validation latency and error rates.

Operational Impact

Maintenance

  • Key Management:
    • Rotation: Automate key rotation using Laravel’s scheduler (e.g., monthly RSA key updates).
    • Backup: Store private keys in secure vaults (e.g., AWS Secrets Manager, HashiCorp Vault).
    • Revocation: Implement a revoked_tokens table with TTLs for short-lived tokens or manual revocation.
  • Dependencies:
    • Monitor PHP extension updates (e.g., openssl) for compatibility.
    • Pin simplejwt version in composer.json to avoid breaking changes.
  • Logging:
    • Log token generation/validation events (e.g., user, timestamp, algorithm, success/failure).
    • Alert on failed validations (e.g., expired tokens, algorithm mismatches).

Support

  • Troubleshooting:
    • Common Issues:
      • Token expiration: Ensure exp claims are correctly set and clocks are synchronized.
      • Algorithm errors: Validate alg headers match the key type (e.g., HS256 for symmetric keys).
      • Key errors: Verify PEM/JWK formats and permissions.
    • Debugging Tools:
      • Use SimpleJWT\JWT::deserialise() to inspect tokens without validation.
      • Add a /debug/token endpoint for introspection (e.g., claims, signatures
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui