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

Symfony Jwt Auth Laravel Package

agven/symfony-jwt-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this package is Symfony-based, Laravel developers will need to adapt it via Symfony Bridge (symfony/http-foundation-bridge) or Laravel Symfony Integration (spatie/symfony). Start by:

  1. Install Dependencies

    composer require firebase/php-jwt spatie/symfony symfony/security-guard
    
  2. Configure Symfony Components Create a Symfony-style security.yaml (or use Laravel’s config/security.php via a custom provider):

    security:
        firewalls:
            api:
                pattern: ^/api
                stateless: true
                guard:
                    authenticators:
                        - Agven\JWTAuthBundle\Security\TokenAuthenticator
        access_control:
            - { path: ^/api/auth, roles: IS_AUTHENTICATED_ANONYMOUSLY, methods: [POST] }
            - { path: ^/api, roles: ROLE_ADMIN }
    
  3. First Use Case: Token Generation Inject the TokenManager into a Laravel service (e.g., AuthService):

    use Agven\JWTAuthBundle\Core\Services\Manager\TokenInterface;
    
    class AuthService {
        public function __construct(private TokenInterface $tokenManager) {}
    
        public function login(string $username, string $password) {
            $user = User::where('username', $username)->firstOrFail();
            if (!Hash::check($password, $user->password)) {
                throw new \Exception('Invalid credentials');
            }
            return $this->tokenManager->createAccessToken($user);
        }
    }
    

Implementation Patterns

Workflow: Token-Based API Authentication

  1. Login Endpoint Use Laravel’s Route::post('/api/auth', [AuthController::class, 'login']) to return a JWT:

    public function login(Request $request) {
        $token = app(AuthService::class)->login(
            $request->username,
            $request->password
        );
        return response()->json(['token' => $token]);
    }
    
  2. Protected Routes Middleware to attach the JWT to requests (Symfony-style):

    use Symfony\Component\HttpFoundation\Request;
    
    class JwtAuthMiddleware {
        public function handle(Request $request, Closure $next) {
            $token = $request->bearerToken();
            if (!$token) throw new \Exception('Token required');
            $user = $this->validateToken($token); // Custom validation
            $request->setUser($user); // Symfony-style user object
            return $next($request);
        }
    }
    
  3. Refresh Tokens Extend the TokenManager to handle refresh logic:

    $refreshToken = $this->tokenManager->createRefreshToken($user);
    $accessToken = $this->tokenManager->refreshAccessToken($refreshToken);
    

Integration Tips

  • Laravel-Symfony Bridge: Use spatie/symfony to share Symfony components (e.g., SecurityBundle) with Laravel.
  • Custom User Provider: Implement UserProviderInterface to fetch users from Laravel’s Eloquent.
  • Token Storage: Store refresh tokens in the database (e.g., refresh_tokens table) with expires_at and revoked_at fields.

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Ecosystem

    • Issue: Symfony’s SecurityBundle expects a UserInterface; Laravel’s Authenticatable won’t work directly.
    • Fix: Create a wrapper:
      class LaravelUser implements UserInterface {
          public function __construct(private \App\Models\User $user) {}
          public function getRoles() { return ['ROLE_ADMIN']; }
          public function getPassword() { return $this->user->password; }
          // ... other required methods
      }
      
  2. Token Validation Overhead

    • Issue: Manual token validation in middleware can slow down requests.
    • Fix: Cache validated tokens (e.g., Redis) or use Symfony’s TokenStorage.
  3. Missing Laravel-Specific Features

    • Issue: No built-in support for Laravel’s HasApiTokens or Sanctum.
    • Fix: Hybrid approach: Use this package for JWT + Sanctum for session cookies.

Debugging

  • Token Decoding Errors: Ensure firebase/php-jwt is configured with the correct secret key (from .env):
    # config/packages/agven_jwt_auth.yaml
    agven_jwt_auth:
        secret_key: '%env(JWT_SECRET)%'
    
  • Symfony Events: Listen to security.authentication.success to log token generation:
    event(new SecurityEvent($event->getAuthenticationToken()));
    

Extension Points

  1. Custom Token Claims Extend TokenManager to add claims (e.g., user metadata):

    $token = $this->tokenManager->createAccessToken($user, [
        'scope' => ['read', 'write']
    ]);
    
  2. Token Revocation Implement a TokenBlacklist service to invalidate tokens:

    class TokenBlacklist {
        public function isRevoked(string $token) {
            return BlacklistedToken::where('token', $token)->exists();
        }
    }
    
  3. Rate Limiting Use Laravel’s throttle middleware to limit token refresh attempts:

    Route::middleware(['throttle:10,1'])->post('/api/refresh', ...);
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium