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 library for creating, signing, verifying, and encrypting JSON Web Tokens (JWT/JWS/JWE). Supports JWK/COSE keys, HMAC/RSA/ECDSA/EdDSA algorithms, and common key management and AES encryption methods.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • RFC Compliance: Full support for JWT (RFC7519), JWS (RFC7515), JWE (RFC7516), JWK (RFC7517), and COSE (RFC9053) ensures alignment with industry standards.
    • Algorithm Diversity: Supports HMAC (HS256/384/512), RSA (RS256/384/512), ECDSA (ES256/384/512), EdDSA, and advanced encryption (AES-GCM, PBES2, ECDH-ES). This covers most use cases for authentication, authorization, and secure data exchange.
    • Key Management: Flexible key handling via KeySet (JWK, PEM, symmetric secrets) simplifies integration with existing infrastructure (e.g., HashiCorp Vault, AWS KMS).
    • Extensibility: Modular design (e.g., AlgorithmInterface, KeyInterface) allows custom algorithms or key types if needed.
    • Laravel Synergy: Works seamlessly with Laravel’s service container, middleware, and authentication systems (e.g., Sanctum, Passport).
  • Cons:

    • Complexity: Broad feature set may introduce unnecessary overhead for simple use cases (e.g., HMAC-only JWTs).
    • Dependency Bloat: Requires gmp, openssl, sodium (for EdDSA/X25519), which may not be enabled in all PHP environments.
    • No Built-in Storage: Keys must be managed externally (e.g., database, filesystem, or cache), adding operational complexity.

Integration Feasibility

  • Laravel Ecosystem:
    • Authentication: Replace or augment Laravel’s default session/auth with JWT-based flows (e.g., API tokens, stateless auth).
    • API Security: Secure API endpoints with JWS/JWE for request validation and data encryption (e.g., sensitive payloads).
    • Third-Party Integrations: Standardized token format for OAuth2 (e.g., with Laravel Passport), OpenID Connect, or SAML bridges.
  • Middleware: Easy to integrate with Laravel’s middleware pipeline for token validation (e.g., ValidateJWT middleware).
  • Caching: Tokens can be cached (e.g., Redis) for performance, with short-lived claims (e.g., exp, nbf) for security.

Technical Risk

  • Key Management:
    • Risk: Improper key rotation or storage (e.g., hardcoded secrets) could lead to security breaches.
    • Mitigation: Use Laravel’s config or environment variables for secrets, and integrate with a key management service (KMS).
  • Algorithm Mismatches:
    • Risk: Incorrect alg/enc headers (e.g., RS256 without RSA keys) may cause runtime errors.
    • Mitigation: Validate algorithms during token creation/decoding (e.g., whitelist allowed algorithms in middleware).
  • Performance:
    • Risk: Asymmetric algorithms (RSA/ECDSA) are slower than HMAC. Overuse could impact latency.
    • Mitigation: Benchmark algorithms and prefer symmetric (HMAC) for high-throughput scenarios.
  • Dependency Conflicts:
    • Risk: Conflicts with other packages using gmp, openssl, or sodium.
    • Mitigation: Test in a staging environment with all dependencies installed.

Key Questions

  1. Use Case Clarity:
    • Will this replace Laravel’s session-based auth, or supplement it (e.g., for APIs)?
    • Are JWE (encrypted tokens) needed, or are JWS (signed tokens) sufficient?
  2. Key Infrastructure:
    • How will keys be stored/rotated? (e.g., database, KMS, or environment variables?)
    • Will multi-tenant environments require per-tenant keys?
  3. Algorithm Selection:
    • Are EdDSA/X25519 required, or can we limit to HMAC/RSA for compatibility?
    • Will custom algorithms or key types be needed?
  4. Error Handling:
    • How should invalid tokens be handled (e.g., 401 vs. 403 responses)?
    • Are custom error codes needed for audit logs?
  5. Compliance:
    • Does the project require FIPS 140-2 compliance? (Note: sodium may not be FIPS-certified in all versions.)
    • Are there regulatory constraints on key storage/usage?

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • PHP 8.0+: Aligns with Laravel 9+/10+ requirements.
    • Service Container: SimpleJWT\Keys\KeySet can be bound as a singleton or resolved dynamically.
    • Middleware: Easily integrated into Laravel’s middleware stack (e.g., app/Http/Middleware/ValidateJWT.php).
    • Artisan Commands: Custom commands for key generation/rotation (e.g., php artisan jwt:generate-key).
  • Database:
    • Store JWKs in json or text columns (e.g., key_sets table with key_id, algorithm, public_key, private_key).
    • Use Laravel’s encrypt for sensitive keys in the database.
  • Caching:
    • Cache KeySet objects in Redis/Memcached to avoid repeated file I/O.
    • Cache token validation results for high-traffic endpoints.

Migration Path

  1. Pilot Phase:
    • Start with a single API endpoint or microservice to test JWT integration.
    • Use HMAC (HS256) for simplicity, then expand to RSA/ECDSA as needed.
  2. Key Infrastructure:
    • Migrate from hardcoded secrets to environment variables or a secrets manager.
    • Implement a key rotation strategy (e.g., kid headers to identify active keys).
  3. Middleware Integration:
    • Replace session-based auth with JWT validation middleware.
    • Example:
      // app/Http/Middleware/ValidateJWT.php
      public function handle(Request $request, Closure $next) {
          $token = $request->bearerToken();
          $keySet = app(KeySet::class);
          try {
              $jwt = JWT::decode($token, $keySet, 'HS256');
              $request->merge(['user' => $jwt->getClaim('sub')]);
          } catch (InvalidTokenException $e) {
              return response('Unauthorized', 401);
          }
          return $next($request);
      }
      
  4. Gradual Rollout:
    • Phase out session cookies for APIs, keeping them for legacy web flows.
    • Use feature flags to enable JWT for specific routes/users.

Compatibility

  • Laravel Packages:
    • Sanctum/Passport: Can be extended to use simplejwt for token generation/validation.
    • Laravel Fortify: Customize to emit JWTs instead of sessions.
  • Frontend:
    • Replace axios interceptors for session cookies with JWT storage (e.g., localStorage or HTTP-only cookies).
  • Legacy Systems:
    • Use JWT::deserialise() to parse tokens from non-Laravel systems without validation.

Sequencing

  1. Setup:
    • Install package: composer require kelvinmo/simplejwt.
    • Configure PHP extensions (gmp, openssl, sodium).
  2. Key Setup:
    • Generate keys (e.g., RSA via openssl genrsa) and store in KeySet.
    • Example:
      // config/jwt.php
      'keys' => [
          'default' => [
              'algorithm' => 'RS256',
              'public_key' => file_get_contents(storage_path('app/jwt/public.pem')),
              'private_key' => file_get_contents(storage_path('app/jwt/private.pem')),
          ],
      ];
      
  3. Token Generation:
    • Create a service to generate tokens (e.g., app/Services/JWTService.php).
  4. Validation:
    • Implement middleware for token validation.
  5. Testing:
    • Test edge cases (expired tokens, malformed payloads, algorithm mismatches).
  6. Monitoring:
    • Log token validation failures and key usage (e.g., kid rotation).

Operational Impact

Maintenance

  • Key Rotation:
    • Pros: kid headers enable smooth rotation (e.g., deprecate old keys after new ones are validated).
    • Cons: Requires coordination across services to update KeySet.
    • Tools: Use Laravel’s scheduler to automate key generation/validation checks.
  • Dependency Updates:
    • Monitor kelvinmo/simplejwt for security patches (e.g., algorithm vulnerabilities).
    • Test updates in staging before production deployment.
  • Documentation:
    • Document key storage locations, rotation procedures, and algorithm choices.

Support

  • Common Issues:
    • Token Expiry: Ensure exp claims are set correctly (e.g., `now()->addHours(1
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests