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

Oauth2 Server Laravel Package

league/oauth2-server

Standards-compliant OAuth 2.0 authorization server for PHP. Protect APIs with bearer access tokens, issue and refresh tokens, and support common grants (auth code, client credentials, device, implicit, password, refresh) with PSR-7 interoperability and RFC support.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Laravel Native Compatibility: While not Laravel-specific, this package integrates seamlessly with Laravel via Laravel Passport (a wrapper built on league/oauth2-server). The core OAuth2 logic is framework-agnostic but adheres to PSR-7 (HTTP messages) and PSR-15 (middleware), making it a natural fit for Laravel’s middleware stack.
    • Modular Design: Supports all major OAuth2 grants (Authorization Code, Client Credentials, Device Code, Implicit, Refresh, Password) and RFCs (JWT, PKCE, Bearer Tokens), aligning with modern API security needs.
    • Extensibility: Interfaces like GrantTypeInterface, CryptKeyInterface, and AuthorizationRequestInterface allow customization (e.g., adding new grants, token storage backends).
    • Security-First: Defaults to secure practices (e.g., PKCE validation, case-insensitive Bearer tokens, JWT leeway for time drift, and sensitive data protection in stack traces).
    • Event-Driven: Emits events (RequestAccessTokenEvent, RequestRefreshTokenEvent) for observability and auditing.
  • Cons:

    • Not a Drop-in Solution: Requires custom implementation or Laravel Passport for full integration. Passport abstracts much of the complexity but may limit fine-grained control.
    • Token Storage: The package itself doesn’t provide persistence; Laravel Passport or a custom solution (e.g., Redis, database) is needed for storing tokens/clients.
    • PSR-7 Dependency: Requires PSR-7 HTTP messages (e.g., laminas/diactoros or nyholm/psr7), adding minor overhead for routing/response handling.

Integration Feasibility

  • Laravel Ecosystem:
    • Passport Integration: Laravel Passport is the de facto choice for OAuth2 in Laravel, built on this package. It handles token storage (via Eloquent), middleware, and API routes out of the box.
    • Custom Implementation: For non-Passport use, the package can be integrated via middleware (e.g., league/oauth2-server middleware) or a service container. Example:
      use League\OAuth2\Server\AuthorizationServer;
      use League\OAuth2\Server\ResourceServer;
      
      $authServer = new AuthorizationServer(
          $grantFactory,
          $tokenRepository,
          $clientRepository,
          $entityManager
      );
      
    • PSR-15 Middleware: Can be used as middleware in Laravel’s pipeline (e.g., for token validation):
      $app->pipe(ResourceServer::class);
      
  • Dependencies:
    • Core: league/oauth2-server + lcobucci/jwt (for JWT support).
    • Laravel: league/oauth2-server + laravel/passport (recommended) or custom PSR-7/PSR-15 setup.
    • Extensions: Optional (e.g., league/uri for URI parsing, symfony/event-dispatcher for events).

Technical Risk

  • Low Risk:
    • Mature Codebase: Actively maintained (last release: 2026-06-25), high test coverage (~90%), and MIT-licensed.
    • Backward Compatibility: Major version 9.x includes breaking changes (e.g., strict typing, event refactoring), but Laravel Passport is updated to support it.
    • Security: Audited (Mozilla Secure Open Source Fund) and compliant with OAuth2/RFCs.
  • Mitigable Risks:
    • Token Storage: Requires custom implementation if not using Passport. Use a library like spatie/laravel-activitylog for auditing.
    • Performance: JWT validation and token generation add minor overhead (~5–10ms per request). Benchmark in staging.
    • PKCE Complexity: If implementing custom grants (e.g., Device Code), ensure PKCE validation is correctly configured to prevent downgrade attacks.
  • Critical Questions:
    1. Will we use Laravel Passport (recommended) or a custom implementation? Passport reduces risk but may limit flexibility.
    2. How will we store tokens/clients? Passport uses Eloquent; custom solutions may require Redis or a database.
    3. Do we need custom grants (e.g., SAML hybrid)? If so, assess the effort to extend GrantTypeInterface.
    4. What’s the token revocation strategy? The package supports revokeRefreshTokens() but requires custom logic for token blacklisting.
    5. How will we handle JWT validation? Leeway settings (e.g., league/oauth2-server's setLeeway) must align with your clock skew tolerance.

Integration Approach

Stack Fit

  • Laravel-Specific:
    • Passport: Ideal for most use cases. Provides:
      • Token storage (Eloquent models).
      • Middleware for route protection (auth:api).
      • Pre-configured grants (Authorization Code, Client Credentials, Refresh).
      • Token revocation via Passport::tokens().
    • Custom Middleware: For non-Passport use, integrate league/oauth2-server as PSR-15 middleware:
      $app->pipe(function (ServerRequestInterface $request) {
          $resourceServer = new ResourceServer(
              $tokenRepository,
              $entityManager
          );
          return $resourceServer->validateAuthenticatedRequest($request);
      });
      
  • Non-Laravel PHP:
    • Works with any PSR-7-compliant framework (e.g., Symfony, Slim). Example with Symfony:
      # config/services.yaml
      League\OAuth2\Server\AuthorizationServer:
          arguments:
              $grantFactory: '@League\OAuth2\Server\GrantFactory'
              $tokenRepository: '@App\Repository\TokenRepository'
              # ...
      
  • Database/Storage:
    • Passport: Uses Eloquent (oauth_clients, oauth_access_tokens, oauth_refresh_tokens).
    • Custom: Implement AccessTokenRepositoryInterface, ClientRepositoryInterface, etc., using Redis, DynamoDB, or a database.

Migration Path

  1. Assess Current Auth:
    • If using API tokens or basic auth, migrate to OAuth2 for scalability and delegation.
    • If using Laravel Sanctum, evaluate whether OAuth2’s granular scopes/grants are needed.
  2. Choose Integration Strategy:
    • Option A (Recommended): Use Laravel Passport.
      • Install: composer require laravel/passport.
      • Run: php artisan passport:install.
      • Configure: Update AuthServiceProvider and add Passport::routes().
    • Option B (Custom): Use league/oauth2-server directly.
      • Install: composer require league/oauth2-server lcobucci/jwt.
      • Implement repositories (e.g., TokenRepository, ClientRepository).
      • Set up middleware/routing.
  3. Test Incrementally:
    • Start with Client Credentials Grant (machine-to-machine).
    • Add Authorization Code Grant (user delegation).
    • Validate PKCE for public clients.
  4. Deprecate Legacy Auth:
    • Use middleware to enforce OAuth2 for protected routes.
    • Example:
      Route::middleware(['auth:api'])->group(function () {
          // Protected routes
      });
      

Compatibility

  • Laravel Versions:
    • Compatible with Laravel 10.x/11.x (Passport v11+ supports PHP 8.2+).
    • Avoid Laravel 8.x if using PHP 8.5+ (Passport may lag in updates).
  • PHP Versions:
    • Requires PHP 8.2–8.5 (as of v9.3.0). Use php:8.2 or php:8.3 in Docker.
  • Dependencies:
    • PSR-7: laminas/diactoros (default) or nyholm/psr7.
    • JWT: lcobucci/jwt (v4.1+ for StrictValidAt support).
    • Events: symfony/event-dispatcher (optional, for custom events).
  • Database:
    • Passport: MySQL/PostgreSQL/SQLite.
    • Custom: Any storage supporting AccessTokenEntityInterface.

Sequencing

  1. Phase 1: Setup
    • Install Passport or league/oauth2-server.
    • Configure repositories (database/Redis).
    • Set up clients (oauth_clients table or custom storage).
  2. Phase 2: Core Grants
    • Implement Authorization Code Grant (web/mobile apps).
    • Implement Client Credentials Grant (services).
  3. Phase 3: Advanced Features
    • Enable PKCE for public clients.
    • Configure **JWT
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle