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

Jwt Refresh Token Bundle Laravel Package

gesdinet/jwt-refresh-token-bundle

Symfony bundle to manage JWT refresh tokens for LexikJWTAuthenticationBundle. Stores and rotates refresh tokens via Doctrine ORM or MongoDB ODM (or custom object manager), with configurable TTL, security, and endpoints. Requires PHP 8.2+ and Symfony 6.4+.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Symfony/LexikJWT Integration: The bundle is a native extension of LexikJWTAuthenticationBundle, making it a seamless fit for Symfony-based APIs relying on JWT for authentication. It aligns with Symfony’s security architecture (firewalls, user providers, event listeners).
  • Token Management: Provides stateless refresh token rotation (single-use or persistent) with configurable TTL, addressing common OAuth2/JWT refresh token patterns.
  • Persistence Flexibility: Supports Doctrine ORM/ODM and custom persistence layers, allowing integration with existing data storage strategies.
  • Extensibility: Customizable via configuration (e.g., cookie-based tokens, TTL updates, user providers) and entity inheritance for domain-specific extensions.

Integration Feasibility

  • Low Coupling: Requires minimal changes to existing auth flows (adds a /token/refresh endpoint and config updates). No breaking changes to LexikJWTAuthenticationBundle.
  • Dependency Alignment: Hard dependency on Symfony 6.4+ and PHP 8.2+, which may require upgrades if not already compliant. Compatible with modern Symfony stacks (Flex, API Platform, etc.).
  • Database Schema: Adds a single refresh_tokens table (ORM) or collection (ODM), requiring a migration. No complex joins or schema conflicts.

Technical Risk

  • Security Risks:
    • Token Leakage: Default JSON response may expose refresh tokens in logs/analytics. Mitigate via cookie config or remove_token_from_body.
    • Replay Attacks: Single-use tokens (single_use: true) prevent replay but require careful handling of token invalidation.
    • HTTPS Dependency: Bundle recommends HTTPS; non-compliance risks token interception.
  • Performance Risks:
    • Token Validation Overhead: Each refresh requires a DB query to validate the token. For high-throughput APIs, consider caching or in-memory stores (e.g., Redis) for the RefreshToken entity.
    • TTL Updates: Enabling ttl_update: true adds write operations on every refresh, increasing DB load.
  • Compatibility Risks:
    • Legacy Systems: Older Symfony/LexikJWT versions (pre-6.4) require the 1.x branch, which may lack features or security patches.
    • Custom Auth Flows: Non-standard JWT issuance (e.g., third-party auth providers) may need adapter layers.

Key Questions

  1. Token Storage:
    • Is the existing database optimized for high-frequency token lookups (e.g., indexed token field)?
    • Should refresh tokens be stored in a dedicated cache (e.g., Redis) instead of the primary DB to reduce latency?
  2. Security Hardening:
    • Are there plans to enforce HTTPS and CORS for token endpoints?
    • Should refresh tokens be scoped to IP/user-agent to mitigate CSRF?
  3. Token Rotation Strategy:
    • Is single-use (single_use: true) required, or can long-lived tokens be used with ttl_update?
    • How will token revocation (e.g., on logout) be handled for non-cookie-based clients?
  4. Monitoring:
    • Are metrics needed for token refresh rates, failed attempts, or expiration patterns?
  5. Fallback Mechanisms:
    • What’s the plan for database downtime? Should tokens be cached or use a fallback store?
  6. Customization Needs:
    • Are additional token claims (e.g., scope, client_id) required for downstream systems?

Integration Approach

Stack Fit

  • Symfony Ecosystem: Ideal for API-first Symfony apps using LexikJWTAuthenticationBundle. Works alongside:
    • API Platform: For GraphQL/REST APIs.
    • Mercure: For real-time token updates.
    • MercureHub: For broadcasting token revocations.
  • Non-Symfony: Not directly applicable; would require rewriting the bundle or using a standalone JWT library (e.g., firebase/php-jwt).
  • Microservices: Can be integrated via shared auth service or token introspection endpoints.

Migration Path

  1. Preparation:
    • Upgrade to Symfony 6.4+ and PHP 8.2+ if not already compliant.
    • Audit existing LexikJWTAuthenticationBundle config for conflicts.
  2. Installation:
    • Add dependencies (gesdinet/jwt-refresh-token-bundle, doctrine/orm or mongodb-odm).
    • Configure config/bundles.php and config/packages/gesdinet_jwt_refresh_token.yaml.
  3. Entity Setup:
    • Generate RefreshToken entity (ORM/ODM) and run migrations.
  4. Security Config:
    • Extend security.yaml to include refresh_jwt firewall and api_refresh_token route.
    • Configure logout event for token invalidation.
  5. Testing:
    • Validate token issuance/refresh with tools like Postman or curl.
    • Test edge cases: expired tokens, single-use tokens, concurrent refreshes.

Compatibility

  • LexikJWTAuthenticationBundle: Required. Ensure versions are compatible (check bundle docs).
  • Doctrine: Works with ORM (v2.10+) and MongoDB ODM (v2.0+). Custom persistence requires implementing RefreshTokenInterface.
  • Custom Auth: If using third-party auth (e.g., Auth0, Keycloak), ensure the bundle’s UserProvider can integrate with your user loader.
  • CORS: Ensure token endpoints (/api/login, /api/token/refresh) are whitelisted in CORS config.

Sequencing

  1. Phase 1: Core Integration
    • Implement basic refresh token flow (login → refresh → access token).
    • Test with a single user provider.
  2. Phase 2: Advanced Features
    • Enable single_use, ttl_update, or cookie-based tokens.
    • Customize RefreshToken entity (e.g., add ip_address field).
  3. Phase 3: Security Hardening
    • Enforce HTTPS, rate-limiting on /api/token/refresh.
    • Add monitoring for token usage patterns.
  4. Phase 4: Scaling
    • Offload token storage to Redis for high-throughput APIs.
    • Implement token revocation via Mercure or a dedicated service.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor gesdinet/jwt-refresh-token-bundle and lexik/jwt-authentication-bundle for security patches.
    • Symfony major version upgrades may require bundle updates (e.g., Symfony 7.x).
  • Schema Changes:
    • New bundle versions may introduce breaking changes (e.g., new config keys). Test thoroughly.
  • Logging:
    • Log token refresh events (success/failure) for auditing. Example:
      # config/services.yaml
      Gesdinet\JWTRefreshTokenBundle\EventListener\RefreshTokenListener:
          tags:
              - { name: kernel.event_listener, event: security.interactive_login, method: onRefreshToken }
      

Support

  • Troubleshooting:
    • Common issues:
      • Token validation failures: Check RefreshToken entity fields (e.g., used_at for single-use tokens).
      • Database errors: Verify migrations and connection settings.
      • CORS issues: Ensure Access-Control-Allow-Origin headers are set.
    • Debugging tools:
      • Enable Symfony’s debug:router and debug:container for config validation.
      • Use bin/console debug:event-dispatcher to inspect LogoutEvent listeners.
  • Documentation:
    • Maintain internal runbooks for:
      • Token revocation procedures.
      • Handling mass token invalidations (e.g., compromised refresh tokens).

Scaling

  • Performance Bottlenecks:
    • Database Load: Refresh token validation queries can scale horizontally with:
      • Read Replicas: Offload token lookups to replicas.
      • Caching: Store tokens in Redis with a short TTL (e.g., 5 minutes), syncing with DB asynchronously.
    • Token Generation: High-volume APIs may need to batch-insert tokens or use bulk operations.
  • Horizontal Scaling:
    • Stateless design allows scaling Symfony workers, but token storage must be shared (DB/Redis).
    • Consider sharding the refresh_tokens table if token volume exceeds 10M+ entries.

Failure Modes

Failure Scenario Impact Mitigation
Database downtime Token validation fails Use Redis as a fallback store for critical tokens.
Token table corruption Lost refresh tokens Regular backups; consider soft deletes (is_valid flag) instead of hard deletes.
Concurrent refresh attacks Token exhaustion Rate-limit `/api/token
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor