tymon/jwt-auth
Laravel JWT authentication package providing token issuing, parsing, refresh, and invalidation using JSON Web Tokens. Integrates with Laravel guards/middleware, supports custom claims and multiple auth providers, and includes docs and testing support.
Start by installing the package via Composer (composer require tymon/jwt-auth), then run php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" to publish the config/jwt.php config file and php artisan jwt:secret to generate a secure signing key in .env. Next, update your User model to implement the JWTSubject contract (requiring getJWTIdentifier() and getJWTCustomClaims() methods) and configure the api guard in config/auth.php to use 'driver' => 'jwt'. Finally, define basic auth routes (/auth/login, /auth/me, etc.) and create an AuthController that uses auth()->attempt() for login and auth()->user() for protected endpoints. This minimal setup enables immediate token-based authentication for API endpoints.
auth()->attempt($credentials) on login to issue tokens, auth()->user() in middleware-protected routes (via auth:api), and auth()->logout()/refresh() for session lifecycle.auth()->claims(['role' => 'admin'])->login($user), accessed later via auth()->payload()->get('role').Authorization: Bearer <token> header (recommended), query param (?token=), or POST field—adjustable via config/jwt.php’s token_prefix and storage_key.config/auth.php (e.g., admin_jwt) and reference explicitly with auth('admin_jwt')->user() for role-based endpoint separation.auth()->setToken($token)->user() for background jobs or CLI tasks where the request context isn’t available, or auth()->tokenById($userId) to pre-generate tokens for onboarding emails.auth()->logout(true) to force "forever" blacklisting (via cache), especially for logout or password change events. Without this, refresh tokens can be reused until expired.JWTSubject implementation must use a unique identifier (typically getKey()), and the model must be serializable (e.g., CanResetPassword traits may cause issues with custom getJWTIdentifier()).auth()->factory()->getTTL() returns minutes—multiply by 60 only when exposing to clients; internal refresh logic uses minutes directly. Changing config/jwt.php’s ttl requires cache invalidation for active blacklists.auth:api middleware runs after request validation (e.g., VerifyCsrfToken exceptions for /api/*) but before route controllers—misordered middleware can cause silent 401s.auth()->payload() to inspect claims in tinker or logs. If auth()->user() returns null, verify token signature validity in jwt.io and check Laravel’s storage/logs for JWTException causes (e.g., expired, invalid signature).JWT_CUSTOM_CLAIMS in config/jwt.php, replace blacklist storage with your own implementation by binding Tymon\JWTAuth\Blacklist, or override the user retrieval logic in config/jwt.php’s user key (e.g., 'user' => 'App\Models\Admin').How can I help you explore Laravel packages today?