Weave 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 Bundle Laravel Package

league/oauth2-server-bundle

Symfony bundle integrating the League OAuth2 server library into your application. A maintained replacement for trikoder/oauth2-bundle, it provides OAuth2 authorization server endpoints with Doctrine persistence support and stays in sync with Symfony.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup (v2.0+)

  1. Verify your runtime — v2.0.0 bumped the required dependency floor:

    • PHP 8.1+ (v1.x supported older runtimes)
    • Symfony 6.4 LTS / 7.x components If you're on an older runtime, stay pinned to ^1.2 of the bundle, or upgrade PHP before adopting v2.
  2. Installation:

    composer require league/oauth2-server-bundle:^2.0 doctrine/doctrine-bundle doctrine/orm
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        League\OAuth2ServerBundle\OAuth2ServerBundle::class => ['all' => true],
    ];
    
  3. Migrating from 1.x — v2.0.0 removed the 1.x backward-compatibility layer. Expect:

    • Old deprecated config keys and legacy service IDs to be gone.
    • Constructor signatures on ClientRepository, AccessTokenRepository, etc. to have changed.
    • Any custom grant or extension that subclassed internal classes to break. Do the upgrade in a branch, run composer why-not league/oauth2-server-bundle 2.0 to surface blockers, then walk the config tree and remove deprecated keys before re-deploying.
  4. Database Migration:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  5. First Use Case:

    • Register a Client:
      php bin/console make:oauth2-client --name="MyAppClient" --redirect-uri="https://yourapp.com/callback"
      
    • Test OAuth Flow:
      curl -X POST \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \
        http://yourapp.test/oauth/token
      
  6. Key Files:

    • config/packages/league_oauth2_server.yaml: Main configuration.
    • src/Entity/: Auto-generated OAuth entities (clients, scopes, tokens).
    • src/Security/: Custom authentication logic (if extending).

Implementation Patterns

Core Workflows

  1. Token Generation:

    • Rely on the built-in endpoints (/oauth/authorize, /oauth/token) for authorization code, implicit, client credentials, password, and refresh flows.
    • Example: wrap/extend the token controller when you need pre-flight business logic:
      // src/Controller/OAuthController.php
      use League\OAuth2\Server\ResourceServer;
      
      class OAuthController extends AbstractController {
          public function token(ResourceServer $server) {
              $request = Request::createFromGlobals();
              $server->validateAuthenticatedRequest($request);
              $token = $server->issueAccessToken();
              return new JsonResponse($token->jsonSerialize());
          }
      }
      
  2. Resource Protection:

    • Protect routes with the resource-server middleware (or an equivalent Laravel middleware mapping):
      protected_route:
          path: /api/protected
          methods: GET
          controller: App\Controller\ProtectedController::index
          defaults:
              _oauth: true
      
    • In controller:
      use League\OAuth2\Server\ResourceServer;
      
      class ProtectedController {
          public function index(ResourceServer $server) {
              $request = Request::createFromGlobals();
              $server->validateAuthenticatedRequest($request);
              return new JsonResponse(['data' => 'protected']);
          }
      }
      
  3. Custom Grant Types (v2 API — no legacy BC adapters):

    • Implement GrantTypeInterface directly; the old 1.x compatibility shims are removed in 2.0.
      use League\OAuth2\Server\Grant\GrantTypeInterface;
      
      class CustomGrant implements GrantTypeInterface {
          public function respondToAccessTokenRequest() { /* ... */ }
      }
      
    • Register in config:
      league_oauth2_server:
          grants:
              custom_grant: App\Security\CustomGrant
      
  4. Scopes and Roles:

    • Define scopes in the database or via YAML:
      league_oauth2_server:
          scopes:
              read: Read access
              write: Write access
      
    • Attach scopes to clients during registration.
  5. User Authentication:

    • Integrate with Symfony security by implementing UserEntityInterface:
      use League\OAuth2\Server\Entity\UserEntityInterface;
      
      class AppUser implements UserEntityInterface {
          public function getIdentifier() { /* ... */ }
      }
      

Integration Tips

  1. Using it from a Laravel app:

    • This is a Symfony bundle — Laravel users will have limited benefit. Prefer laravel/passport for idiomatic Laravel support. If you must bridge, route through Symfony\Component\HttpFoundation and adapt the DI container manually; do not assume facades map to bundle services.
    • For a bridge, wrap in a service that translates Illuminate\Http\Request to a SymfonyRequest before hitting the ResourceServer.
  2. Testing:

    • Mock ClientRepositoryInterface / ResourceOwnerRepositoryInterface and exercise the AuthorizationServer / ResourceServer directly. This sidesteps the bundle and is stable across the v1→v2 jump.
      $clientRepo = $this->createMock(ClientRepositoryInterface::class);
      $clientRepo->method('getClientEntity')->willReturn($clientEntity);
      $server = new Server($clientRepo, $accessTokenRepo, $scopeRepo, $privateKey, $encryptionKey);
      
  3. Caching:

    league_oauth2_server:
        cache:
            enabled: true
            pool: cache.app
    
  4. Logging:

    league_oauth2_server:
        debug: true
    

Gotchas and Tips

Pitfalls

  1. v2.0.0 is a hard break from 1.x:

    • The BC layer was removed — do not assume 1.x config keys, deprecated services, or internal class subclassing still works. Run bin/console debug:container --tag=league_oauth2_server.* to confirm services are still registered after upgrade.
    • Fix: Walk the config tree, remove deprecated options, and re-run migrations. Prefer upgrading in a branch with the full test suite.
  2. Dependency floor jumps:

    • v2.0.0 requires PHP 8.1+ and Symfony 6.4+. If your CI matrix or a downstream package pins older versions, composer update will fail with Your requirements could not be resolved. Check with composer why-not before blaming the bundle.
  3. Database Schema Mismatches:

    • Always regenerate and run migrations after a major bump. Auto-generated entity classes (ClientEntity, AccessTokenEntity, etc.) can change between versions.
    php bin/console doctrine:migrations:diff --complete
    
  4. CSRF Protection:

    • The bundle does not handle CSRF for authorization requests by default. Add Symfony's CsrfTokenListener where applicable.
  5. Token Expiry:

    league_oauth2_server:
        access_token_lifetime: 7200
        refresh_token_lifetime: 2592000  # or null for non-expiring (not recommended)
    
  6. Scope Validation:

    • Scopes are not auto-validated against user roles. Check explicitly:
      $scopes = $server->getRequestedScopes();
      if (!in_array('read', $scopes)) {
          throw new \League\OAuth2\Server\Exception\OAuthServerException(
              'insufficient_scope',
              'The requested scope is invalid.',
              \League\OAuth2\Server\ResponseTypes\AccessTokenResponse::class
          );
      }
      
  7. Client Secret Handling:

    • Never hardcode secrets. Use env vars and reference them from config:
      league_oauth2_server:
          private_key: '%env(OAUTH_PRIVATE_KEY)%'
          encryption_key: '%env(OAUTH_ENCRYPTION_KEY)%'
      
  8. CORS Issues:

    nelmio_cors:
        paths:
            '^/oauth/':
                allow_origins: ['%env(APP_ALLOWED_ORIGINS)%']
                allow_methods: ['POST', 'OPTIONS']
    
  9. Middleware Order:

    • ResourceServerMiddleware must run after the firewall middleware, otherwise the security context isn't populated when the resource server validates the token.

Debugging Tips

  1. Enable Debug Mode:

    league_oauth2_server:
        debug: true
    
    • Check var/log/dev.log for detailed traces.
  2. Token Validation Errors:

    • Examine error / error_description in failed token responses:
      • invalid_client: client ID/secret mismatch.
      • invalid_grant: bad authorization code or expired refresh token.
      • unsupported_grant_type: grant not enabled for the client.
  3. Database Debugging:

    doctrine:
        dbal:
            logging: true
            profiling: true
    
  4. Post-upgrade checklist (v1 → v2):

    • Compare generated services: bin/console debug:container | grep oauth2.
    • Diff your local config/packages/league_oauth2_server.yaml against the v2 reference config — removed keys will silently be ignored or rejected depending on the tree builder.
    • Re-run bin/console cache:clear --no-warmup and then warm up to surface constructor signature changes in repositories, grant types, and response types.
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.
robertmarney/lara-hierarchial-collections
simonschaufi/rule-doc-generator
emissaoja/emissaoja
blackbricksoftware/gravityforms-civicrm-form-processor
al-rahabi/fancy-crud
jinas/dhivatar-component
mltstephane/laravel-quality
bernskiold/laravel-talentlms
bernskioldmedia/laravel-form-architect
youbar/easy-crud
c-point-labs/laravel-hostyourai
dbravoan/dbcms-admin-theme-dbcms
dbravoan/dbcms-theme-db-cyber
dbravoan/dbcms-blocks-basic
dbravoan/dbcms-module-content-audit
dbravoan/dbcms-module-ai-assistant
paygate-to/paygate-php
padosoft/askmydocs-connector-base
defstudio/supercharged-carbon
bernskioldmedia/laravel-matomo