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

Passport Laravel Package

laravel/passport

Laravel Passport provides a full OAuth2 server for Laravel, making API authentication simple with access tokens, personal access tokens, and client credentials. Officially maintained, with extensive docs and integrations for securing first- and third-party APIs.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel/passport
   php artisan passport:install
  • Runs migrations, creates OAuth tables, and generates encryption keys.
  • Automatically registers Passport::routes() in AuthServiceProvider.
  1. First Use Case:

    • API Authentication: Protect routes with auth:api middleware.
      Route::middleware('auth:api')->group(function () {
          Route::get('/user', function (Request $request) {
              return $request->user();
          });
      });
      
    • Token Generation: Use Passport::token() in tests or manual scenarios:
      $token = Passport::actingAs($user)->createToken('API Token')->accessToken;
      
  2. Key Files:

    • config/auth.php: Ensure api guard uses passport driver.
    • app/Providers/AuthServiceProvider.php: Verify Passport::routes() is called.

Implementation Patterns

Core Workflows

1. Token-Based Authentication

  • Client Credentials Flow (Machine-to-Machine):
    $client = \Laravel\Passport\Client::find(1);
    $token = $client->accessToken;
    $response = Http::withToken($token)->get('api/endpoint');
    
  • Authorization Code Flow (Web Apps): Redirect users to /oauth/authorize with client_id and redirect_uri. Exchange code for token via /oauth/token endpoint.

2. Personal Access Tokens (PATs)

  • Issue manually:
    $token = $user->createToken('My PAT')->accessToken;
    
  • Revoke:
    $user->tokens()->delete();
    

3. Scopes and Permissions

  • Assign scopes to tokens:
    $token = $user->createToken('Admin Access', ['admin', 'read']);
    
  • Validate in middleware:
    public function handle(Request $request, Closure $next) {
        if (!$request->user()->tokenCan('admin')) {
            abort(403);
        }
        return $next($request);
    }
    

4. Testing

  • Mock authentication:
    Passport::actingAs($user);
    // or for clients
    Passport::actingAsClient($client);
    
  • Assert token validation:
    $response = $this->withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->get('/api/endpoint');
    $response->assertOk();
    

Integration Tips

1. Custom User Models

  • Ensure your User model implements Laravel\Passport\HasApiTokens:
    use Laravel\Passport\HasApiTokens;
    
    class User extends Authenticatable {
        use HasApiTokens, Notifiable;
    }
    
  • Override findForPassport if using non-standard auth identifiers:
    public static function findForPassport($identifier) {
        return static::where('email', $identifier)->first();
    }
    

2. Custom Clients

  • Extend Laravel\Passport\Client for custom logic:
    class CustomClient extends \Laravel\Passport\Client {
        public function isInternal() {
            return $this->name === 'Internal Service';
        }
    }
    
  • Register in AuthServiceProvider:
    Passport::useClientModel(CustomClient::class);
    

3. Middleware Customization

  • Register custom middleware for token validation:
    Passport::tokensExpireIn(CarbonInterval::hours(1));
    Passport::refreshTokensExpireIn(CarbonInterval::days(30));
    Passport::personalAccessTokensExpireIn(CarbonInterval::never());
    
  • Add middleware to HandlePersonalAccessTokens:
    Passport::personalAccessTokensCanSee([YourMiddleware::class]);
    

4. Token Lifecycle

  • Purge Revoked Tokens:
    php artisan passport:purge
    
  • Custom Token Model: Extend Laravel\Passport\Token to add fields (e.g., ip_address):
    class CustomToken extends \Laravel\Passport\Token {
        protected $fillable = ['ip_address'];
    }
    

5. Headless Mode (Jetstream/Breeze)

  • Disable default routes/views:
    Passport::ignoreRoutes();
    Passport::ignoreMigrations();
    
  • Manually handle token issuance in your auth stack.

Gotchas and Tips

Pitfalls

1. Token Impersonation

  • Issue: Client credentials tokens could impersonate users if user_id matches client_id (fixed in v13.7.1).
  • Fix: Use UUIDs for client IDs or validate explicitly:
    if ($token->user_id === $client->id) {
        throw new \League\OAuth2\Server\Exception\OAuthServerException(
            'User impersonation detected'
        );
    }
    

2. Missing passport:hash

  • Issue: Forgetting to run php artisan passport:hash after passport:install causes token generation failures.
  • Fix: Always run:
    php artisan passport:hash
    

3. Scopes Not Persisted

  • Issue: Scopes assigned to tokens may not persist if not saved:
    // Wrong: Scopes not saved
    $token = $user->createToken('Test', ['scope1']);
    // Correct:
    $token = $user->createToken('Test')->accessToken;
    $token->scopes()->attach(['scope1']);
    $token->save();
    

4. Token Guard Configuration

  • Issue: TokenGuard may fail if auth.guard is misconfigured.
  • Fix: Ensure config/auth.php:
    'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    

5. Client Secret Exposure

  • Issue: Public clients (e.g., SPAs) have no secrets; confidential clients require secure storage.
  • Fix: Use environment variables for secrets:
    PASSPORT_CLIENT_SECRET=your_secure_secret
    

6. Migration Conflicts

  • Issue: Running passport:install after custom migrations may cause conflicts.
  • Fix: Review oauth_clients table schema in UPGRADE.md and merge changes manually.

Debugging Tips

1. Token Validation Errors

  • Check token format (must be Bearer <token>).
  • Verify token hasn’t expired (use tinker to inspect):
    php artisan tinker
    >>> \Laravel\Passport\Token::find(1)->expires_at
    

2. Authorization Failures

  • Enable OAuth2 debug mode:
    Passport::enableDebugMode();
    
  • Check logs for oauth-server exceptions.

3. Client Registration Issues

  • Validate redirect_uri matches registered URIs (case-sensitive).
  • Ensure grant_types include required flows (e.g., authorization_code).

4. Performance

  • Slow Token Lookups: Add indexes to oauth_access_tokens:
    Schema::table('oauth_access_tokens', function (Blueprint $table) {
        $table->index('user_id');
        $table->index('client_id');
    });
    
  • Token Revocation: Use Passport::purge() periodically to clean revoked tokens.

Extension Points

1. Custom Grant Types

  • Implement League\OAuth2\Server\Grant\GrantInterface:
    class CustomGrant implements GrantInterface {
        public function respondToAccessTokenRequest() { /* ... */ }
    }
    
  • Register in AuthServiceProvider:
    Passport::grantType(CustomGrant::class);
    

2. Token Storage

  • Override TokenRepository to use Redis or another store:
    Passport::tokens()->useCustomRepository(CustomTokenRepository::class);
    

3. Event Hooks

  • Listen to OAuth events:
    Passport::tokensGranted(function ($user, $token) {
        // Log token issuance
    });
    
  • Available events: tokensCreated, tokensRefreshed, tokensRevoked.

4. Response Customization

  • Modify error responses:
    Passport::exceptionHandling
    
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai