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 an OAuth2 server for Laravel, enabling API authentication with personal access tokens, password and authorization code grants, and client credentials. Integrates with Laravel’s auth system for secure, standards-based token issuing.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

Laravel Passport is a first-class fit for Laravel-based applications requiring OAuth2 authentication. It integrates seamlessly with Laravel’s ecosystem, leveraging:

  • Laravel’s built-in authentication system (users, guards, providers).
  • TokenGuard for API authentication, replacing traditional session-based auth.
  • Middleware support (e.g., auth:api) for route protection.
  • Headless mode (compatible with Laravel Jetstream/Breeze) for decoupled auth flows.
  • Extensible grant types (authorization code, client credentials, password, refresh tokens, and device codes).

Key architectural strengths:

  1. Decoupled design: Separates OAuth2 logic from business logic, enabling modular API development.
  2. Standard compliance: Adheres to OAuth2 RFCs (e.g., RFC 6749, RFC 7662) while abstracting complexity.
  3. Laravel-native: Uses Eloquent models (Client, Token, RefreshToken) and migrations, reducing boilerplate.
  4. Token personalization: Supports scopes, revocation, and custom claims via token models.

Potential misfits:

  • Non-Laravel stacks: Requires Laravel’s dependency injection, Eloquent ORM, and routing system.
  • Microservices with polyglot persistence: Assumes a single database for OAuth entities (though this can be mitigated with custom storage adapters).

Integration Feasibility

Aspect Feasibility Notes
Laravel Version High Supports Laravel 10+ (tested up to v13.x). Backward-compatible with minor adjustments.
Database Schema Medium Requires oauth_clients, oauth_access_tokens, oauth_refresh_tokens, and oauth_scopes tables.
Existing Auth System High Integrates with Laravel’s User model or custom auth providers via findForPassport().
API Gateway High Works with API gateways (e.g., Kong, AWS ALB) via token validation middleware.
Third-Party Clients High Supports public/confidential clients (e.g., SPAs, mobile apps, server-to-server).
Customization High Extensible via events (Registered, Revoked), middleware, and token model overrides.

Critical dependencies:

  • league/oauth2-server (v9.x): Core OAuth2 logic.
  • firebase/php-jwt: JWT token handling (v6+).
  • Laravel’s hash helper: For client secret hashing.

Technical Risk

Risk Area Severity Mitigation
Migration Complexity Medium Schema changes in v13.x (e.g., UUID clients, table refactoring) require careful backward migration.
Token Revocation Low Built-in revocation logic, but custom scopes/claims may need manual cleanup.
Performance Medium Token validation adds overhead (~1–5ms per request). Benchmark under load; consider caching.
Security High Defaults are secure (e.g., hashed secrets, CSRF protection), but misconfigurations (e.g., public clients with secrets) risk exposure.
Grant Type Support Low All common grants are supported, but niche flows (e.g., SAML) require custom middleware.
Deprecations Low JSON API deprecated in v13.x; upgrade path is documented.
PHP 8.5+ Compatibility Low Tested and compatible, but some legacy code may need adjustments.

Key questions for the TPM:

  1. Auth Flow Requirements:
    • Are device codes or client credentials grants needed? (Both are supported but may require additional middleware.)
    • Will personal access tokens (PATs) be used for admin APIs? (Enabled by default but configurable.)
  2. Token Lifecycle:
    • What are the revocation policies (e.g., auto-revoke after inactivity)?
    • Are custom claims or nested scopes required? (Extensible via token model.)
  3. Client Management:
    • How will client secrets be rotated? (Manual or automated via Client model events.)
    • Are dynamic client registration or JWKS needed? (Requires custom endpoints.)
  4. Performance:
    • What is the expected QPS for token validation? (Consider TokenGuard caching or Redis.)
  5. Compliance:
    • Are there audit logging requirements for OAuth events? (Extend via events or middleware.)
  6. Multi-Tenancy:
    • How will tenant isolation be handled? (Scopes or custom Client model attributes.)
  7. Fallback Mechanisms:
    • What’s the plan for token validation failures (e.g., database downtime)? (Circuit breakers or fallback guards.)

Integration Approach

Stack Fit

Laravel Passport is optimized for:

  • Laravel-based APIs (Lumen, Laravel 10+).
  • Monolithic architectures with tightly coupled auth and business logic.
  • Headless APIs (e.g., mobile apps, SPAs) using Jetstream/Breeze.
  • Server-to-server integrations (client credentials grant).

Less ideal for:

  • Non-Laravel backends (Node.js, Go, etc.): Requires custom OAuth2 server implementation.
  • Polyglot persistence: Assumes relational database (though adapters can be built).
  • Edge/Serverless: Cold starts may impact token validation latency.

Migration Path

Phase 1: Setup (1–2 weeks)

  1. Prerequisites:
    • Laravel 10+ application.
    • Database with Eloquent support.
    • Composer installed.
  2. Installation:
    composer require laravel/passport
    php artisan passport:install
    
  3. Configuration:
    • Publish config: php artisan vendor:publish --provider="Laravel\Passport\PassportServiceProvider".
    • Configure config/auth.php to use TokenGuard.
    • Set up App\User (or custom model) to implement Laravel\Passport\HasApiTokens.
  4. Database Migrations:
    • Run php artisan migrate to create OAuth tables.
    • For upgrades from v12.x: Follow upgrade guide.

Phase 2: Core Integration (2–3 weeks)

  1. Token Guard:
    • Protect API routes with auth:api middleware.
    • Example:
      Route::middleware(['auth:api'])->get('/user', function (Request $request) {
          return $request->user();
      });
      
  2. Client Registration:
    • Register clients via Client model or admin UI (e.g., Laravel Nova).
    • Example:
      $client = Client::create([
          'name' => 'Mobile App',
          'secret' => Str::random(40),
          'redirect' => 'myapp://callback',
      ]);
      
  3. Grant Flows:
    • Authorization Code: For SPAs/mobile apps.
    • Client Credentials: For server-to-server.
    • Password Grant: For trusted clients (disable if not needed).
    • Refresh Tokens: Enable via Passport::enableRefreshTokens().
  4. Scopes:
    • Define scopes in oauth_scopes table or via migrations.
    • Attach to tokens/clients:
      $token->scopes()->attach(['read', 'write']);
      

Phase 3: Advanced Customization (1–2 weeks)

  1. Custom Token Model:
    • Extend Laravel\Passport\Token to add claims:
      class CustomToken extends Token {
          public function getCustomClaim() {
              return $this->claims['custom'] ?? null;
          }
      }
      
  2. Middleware:
    • Add custom validation:
      Passport::tokensExpireIn(CarbonInterval::hours(1));
      Passport::refreshTokensExpireIn(CarbonInterval::days(30));
      Passport::personalAccessTokensExpireIn(never());
      
  3. Events:
    • Listen to Registered, Revoked, etc.:
      Passport::tokensRegistered(function ($user, $token) {
          // Log or notify
      });
      
  4. Testing:
    • Use Passport::actingAs() for API tests:
      Passport::actingAs($user, ['read']);
      

Phase 4: Deployment (1 week)

  1. Token Storage:
    • Ensure oauth_access_tokens table is indexed for performance.
  2. Security Hardening:
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport