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:
Install Dependencies
composer require firebase/php-jwt spatie/symfony symfony/security-guard
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 }
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);
}
}
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]);
}
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);
}
}
Refresh Tokens
Extend the TokenManager to handle refresh logic:
$refreshToken = $this->tokenManager->createRefreshToken($user);
$accessToken = $this->tokenManager->refreshAccessToken($refreshToken);
spatie/symfony to share Symfony components (e.g., SecurityBundle) with Laravel.UserProviderInterface to fetch users from Laravel’s Eloquent.refresh_tokens table) with expires_at and revoked_at fields.Symfony vs. Laravel Ecosystem
SecurityBundle expects a UserInterface; Laravel’s Authenticatable won’t work directly.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
}
Token Validation Overhead
TokenStorage.Missing Laravel-Specific Features
HasApiTokens or Sanctum.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)%'
security.authentication.success to log token generation:
event(new SecurityEvent($event->getAuthenticationToken()));
Custom Token Claims
Extend TokenManager to add claims (e.g., user metadata):
$token = $this->tokenManager->createAccessToken($user, [
'scope' => ['read', 'write']
]);
Token Revocation
Implement a TokenBlacklist service to invalidate tokens:
class TokenBlacklist {
public function isRevoked(string $token) {
return BlacklistedToken::where('token', $token)->exists();
}
}
Rate Limiting
Use Laravel’s throttle middleware to limit token refresh attempts:
Route::middleware(['throttle:10,1'])->post('/api/refresh', ...);
How can I help you explore Laravel packages today?