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 Auth Laravel Package

php-open-source-saver/jwt-auth

Laravel JWT authentication package (fork of tymondesigns/jwt-auth) maintained by PHP Open Source Saver. Provides the same API with a new namespace, easy migration, and adds new features and ongoing support. Full docs available online.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require php-open-source-saver/jwt-auth

Publish the config file:

php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider" --tag=config
  1. Configure Auth Guard: Update config/auth.php to include the JWT guard:

    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
    
  2. First Use Case: Generate a token for a user in a controller:

    use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
    
    $user = User::find(1);
    $token = JWTAuth::fromUser($user);
    return response()->json(['token' => $token]);
    
  3. Protect Routes: Use middleware in routes/api.php:

    Route::middleware('auth:api')->group(function () {
        Route::get('/user', function () {
            return response()->json(auth()->user());
        });
    });
    
  4. Verify Token in Requests: Send the token in the Authorization header:

    Authorization: Bearer <token>
    

Key Configuration

  • Check config/jwt.php for settings like:
    • secret: Encryption key (generate with php artisan jwt:secret).
    • ttl: Token expiration time (e.g., 60 minutes).
    • refresh_ttl: Refresh token TTL.
    • blacklist_enabled: Enable token blacklisting.

Implementation Patterns

Common Workflows

1. Token Generation and Validation

  • Generate Token:
    $token = JWTAuth::fromUser($user);
    
  • Refresh Token:
    $refreshedToken = JWTAuth::refresh($token);
    
  • Validate Token:
    if (!$token = JWTAuth::parseToken()) {
        return response()->json(['error' => 'Invalid token'], 401);
    }
    

2. Authentication Middleware

  • Use the auth:api middleware for protected routes:
    Route::middleware('auth:api')->get('/profile', function () {
        return auth()->user();
    });
    
  • Customize middleware logic by extending JWTMiddleware:
    namespace App\Http\Middleware;
    
    use PHPOpenSourceSaver\JWTAuth\Middleware\GetUserFromToken;
    use Closure;
    
    class CustomJWTMiddleware extends GetUserFromToken
    {
        public function handle($request, Closure $next)
        {
            if (!$this->auth->check()) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
            return $next($request);
        }
    }
    

3. Token Blacklisting

  • Blacklist a token (e.g., on logout):
    JWTAuth::invalidate($token);
    
  • Check if a token is blacklisted:
    if (JWTAuth::isBlacklisted($token)) {
        return response()->json(['error' => 'Token revoked'], 401);
    }
    

4. Custom Claims

  • Attach custom claims when generating a token:
    $customClaims = ['role' => 'admin', 'scope' => ['read', 'write']];
    $token = JWTAuth::fromUser($user, $customClaims);
    
  • Access claims in middleware or controllers:
    $token = JWTAuth::getToken();
    $claims = JWTAuth::getPayload($token);
    

5. Event Listeners

  • Listen for JWT events (e.g., jwt.blacklisted, jwt.refresh):
    JWTAuth::event(function ($event) {
        if ($event instanceof JWTBlacklistEvent) {
            Log::info('Token blacklisted: ' . $event->token);
        }
    });
    

6. Multi-Guard Support

  • Configure multiple guards in config/auth.php:
    'guards' => [
        'api' => ['driver' => 'jwt', 'provider' => 'users'],
        'admin' => ['driver' => 'jwt', 'provider' => 'admins', 'ttl' => 3600],
    ],
    
  • Use guards explicitly:
    $adminToken = JWTAuth::guard('admin')->fromUser($adminUser);
    

7. Cookie-Based Authentication

  • Configure cookie settings in config/jwt.php:
    'cookie' => [
        'enabled' => true,
        'domain' => null,
        'path' => '/',
        'secure' => env('APP_ENV') === 'production',
        'http_only' => true,
        'same_site' => 'lax',
        'cookie_key_name' => 'jwt_token', // Custom cookie name
    ],
    
  • Set the token as a cookie:
    return response()->json(['message' => 'Logged in'])
        ->cookie('jwt_token', $token, $minutes = 60);
    

8. Testing

  • Use JWTAuth in tests:
    $user = User::factory()->create();
    $token = JWTAuth::fromUser($user);
    
    $response = $this->withHeader('Authorization', 'Bearer ' . $token)
        ->get('/api/protected');
    

Integration Tips

Laravel Sanctum/Laravel Passport

  • Use JWT for stateless APIs and Sanctum/Passport for session-based auth:
    // Example: Hybrid auth flow
    if ($request->hasHeader('Authorization')) {
        // JWT auth
        $token = $request->bearerToken();
        if (!$token) return response()->json(['error' => 'Unauthorized'], 401);
        JWTAuth::parseToken();
    } else {
        // Sanctum/Passport auth
        $this->authenticateWithSanctum();
    }
    

API Rate Limiting

  • Combine with Laravel's rate limiting:
    Route::middleware(['auth:api', 'throttle:60,1'])->get('/api/data', function () {
        return response()->json(['data' => '...']);
    });
    

CORS Configuration

  • Ensure CORS allows the Authorization header:
    // config/cors.php
    'paths' => ['api/*'],
    'allowed_headers' => ['*'],
    'allowed_methods' => ['*'],
    'exposed_headers' => ['Authorization'],
    

Octane Compatibility

  • The package supports Laravel Octane for high-performance APIs:
    php artisan octane:start
    

Gotchas and Tips

Pitfalls

1. Token Expiration Handling

  • Issue: Tokens expire silently, leading to TokenNotProvidedException or TokenExpiredException.
  • Fix: Always check for token validity:
    try {
        if (!$token = JWTAuth::parseToken()) {
            return response()->json(['error' => 'Token not provided'], 401);
        }
        $user = JWTAuth::authenticate();
    } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
        return response()->json(['error' => 'Token expired'], 401);
    } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
        return response()->json(['error' => 'Token invalid'], 401);
    }
    

2. Secret Key Management

  • Issue: Forgetting to regenerate the secret key after updating config/jwt.php.
  • Fix: Use the jwt:secret artisan command:
    php artisan jwt:secret
    
  • Tip: Store the secret in environment variables for better security:
    JWT_SECRET=your_secure_secret_here
    

3. Blacklist Configuration

  • Issue: Blacklisted tokens may not be enforced if blacklist_enabled is false in config/jwt.php.
  • Fix: Ensure the config is set:
    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
    

4. Carbon Version Conflicts

  • Issue: Carbon v2 vs. v3 compatibility issues (e.g., addMinutes method).
  • Fix: The package supports both versions, but ensure your composer.json aligns:
    "require": {
        "nesbot/carbon": "^2.66 || ^3.0"
    }
    

5. Token Refresh Edge Cases

  • Issue: Refreshing a token may fail if the original token is already blacklisted.
  • Fix: Check for blacklisted tokens before refreshing:
    if (JWTAuth::isBlacklisted($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