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

lucadegasperi/oauth2-server-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lucadegasperi/oauth2-server-laravel
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        LucaDegasperi\OAuth2Server\OAuthServiceProvider::class,
    ],
    
  2. Publish Config:

    php artisan vendor:publish --provider="LucaDegasperi\OAuth2Server\OAuthServiceProvider"
    

    Configure config/oauth2-server.php (e.g., set private_key_path, encryption_key, and grant_types).

  3. First Use Case:

    • Authorization Endpoint: Test the /oauth/authorize route with a client ID (e.g., http://your-app.test/oauth/authorize?client_id=test_client&redirect_uri=http://your-app.test/callback&response_type=code).
    • Token Endpoint: Exchange a code for a token via /oauth/token (POST request with grant_type=authorization_code).

Where to Look First

  • Documentation: League OAuth2 Server Docs (this package is a Laravel bridge).
  • Config File: config/oauth2-server.php (adjust encryption keys, storage, and grant types).
  • Middleware: app/Http/Middleware/OAuth2ServerMiddleware.php (for protecting routes).
  • Routes: routes/web.php or routes/api.php (define /oauth/authorize, /oauth/token, etc.).

Implementation Patterns

Core Workflows

  1. Client Registration:

    • Store client IDs/secrets in the oauth_clients table (or your custom storage).
    • Example migration:
      php artisan vendor:publish --tag=migrations
      php artisan migrate
      
  2. Grant Types:

    • Authorization Code: For web apps (redirect flow).
      // In a controller:
      $request = new \Laravel\Lumen\Http\Request();
      $server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
      $server->setStorageData('oauth_clients', $clientId);
      $authRequest = $server->validateAuthorizationRequest();
      
    • Password Grant: For trusted clients (direct token exchange).
      $server->validateCredentials($username, $password);
      $server->issueAccessToken();
      
  3. Resource Server:

    • Protect API routes with middleware:
      Route::group(['middleware' => 'oauth'], function () {
          Route::get('/api/user', 'UserController@getUser');
      });
      
    • Validate tokens in controllers:
      $request = app('request');
      $server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
      $resourceOwner = $server->validateAuthenticatedRequest();
      
  4. Custom Storage:

    • Extend LucaDegasperi\OAuth2Server\Storage\StorageInterface for Eloquent or custom storage:
      class CustomStorage implements StorageInterface {
          public function getClient($clientId) {
              return Client::where('id', $clientId)->first();
          }
          // Implement other methods...
      }
      
    • Bind in AppServiceProvider:
      $this->app->bind(
          \LucaDegasperi\OAuth2Server\Storage\StorageInterface::class,
          CustomStorage::class
      );
      

Integration Tips

  • Lumen: Use the OAuth2ServerMiddleware in $app->middleware().
  • CORS: Configure CORS for /oauth/token if using AJAX (e.g., with fruitcake/laravel-cors).
  • Logging: Enable debug logging in config/oauth2-server.php:
    'debug' => env('APP_DEBUG', false),
    
  • Testing: Use LucaDegasperi\OAuth2Server\Tests\TestCase as a base for PHPUnit tests.

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • This package is not maintained for Laravel 5.3+. Use Laravel Passport instead for new projects.
    • If stuck with this package, pin the version in composer.json:
      "lucadegasperi/oauth2-server-laravel": "2.0.0"
      
  2. Storage Backend:

    • Default storage uses sessions, which may not persist across requests. Switch to database storage:
      'storage' => [
          'class' => \LucaDegasperi\OAuth2Server\Storage\DatabaseStorage::class,
          'table_clients' => 'oauth_clients',
          'table_access_tokens' => 'oauth_access_tokens',
          'table_scopes' => 'oauth_scopes',
      ],
      
  3. CSRF Issues:

    • The /oauth/authorize endpoint requires CSRF protection. Add to VerifyCsrfToken middleware:
      protected $except = [
          'oauth/authorize',
      ];
      
  4. Token Expiry:

    • Default token expiry is 1 hour. Customize in config:
      'access_token_lifetime' => 3600, // 1 hour in seconds
      
  5. Redirect URIs:

    • Always validate redirect_uri in client registration to prevent open redirects.

Debugging

  1. Enable Debug Mode:

    'debug' => true,
    

    Check logs for detailed OAuth2 flow errors.

  2. Common Errors:

    • invalid_request: Missing or malformed parameters (e.g., client_id, redirect_uri).
    • invalid_client: Incorrect client ID/secret or unregistered client.
    • unsupported_grant_type: Requested grant type not enabled in config.
    • invalid_scope: Requested scope not configured for the client.
  3. Token Validation:

    • Manually validate tokens for debugging:
      $server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
      try {
          $resourceOwner = $server->validateAuthenticatedRequest();
      } catch (\League\OAuth2\Server\Exception\TokenExpiredException $e) {
          // Handle expired token
      }
      

Extension Points

  1. Custom Grant Types:

    • Extend \League\OAuth2\Server\Grant\GrantInterface and register in config:
      'grants' => [
          \League\OAuth2\Server\Grant\AuthorizationCodeGrant::class,
          \League\OAuth2\Server\Grant\PasswordGrant::class,
          \App\Grants\CustomGrant::class,
      ],
      
  2. Scopes:

    • Add custom scopes by extending \League\OAuth2\Server\ScopeInterface and binding in AppServiceProvider:
      $this->app->bind(
          \League\OAuth2\Server\ScopeInterface::class,
          \App\Scopes\CustomScope::class
      );
      
  3. Response Types:

    • Support implicit flow (deprecated but sometimes needed):
      'response_types' => ['code', 'token'], // Enable 'token' for implicit
      
  4. Event Listeners:

    • Listen to OAuth2 events (e.g., access_token_created):
      \Event::listen('oauth.access_token_created', function ($token) {
          // Custom logic (e.g., log token creation)
      });
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui