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

binhvd/oauth2-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this bundle is Symfony-based, Laravel developers must use a bridge like symfony/bridge or manually adapt it. Start by:

  1. Install via Composer (adapted for Laravel):

    composer require bshaffer/oauth2-server-bundle
    
  2. Register the Bundle (in config/app.php):

    'providers' => [
        // ...
        Symfony\Bridge\Laravel\ServiceProvider::class,
        Bshaffer\OAuth2ServerBundle\OAuth2ServerBundle::class,
    ],
    
  3. Publish Config (adapted for Laravel):

    php artisan vendor:publish --provider="Bshaffer\OAuth2ServerBundle\OAuth2ServerBundle" --tag=config
    

    Update config/oauth2.php with your database/grant type settings.

  4. Define Routes (in routes/api.php):

    Route::post('/token', 'OAuth2Controller@token')->name('oauth2.token');
    
  5. First Use Case: Test with curl:

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_SECRET" \
    http://your-app.test/token
    

Implementation Patterns

Core Workflows

  1. Token Generation:

    • Use the OAuth2Controller to handle /token requests. Extend handleTokenRequest() to customize logic:
      public function token(Request $request)
      {
          $server = app('oauth2.server');
          $server->addGrantType(app('oauth2.grant_type.authorization_code'));
          return $server->handleTokenRequest($request, app('oauth2.response'));
      }
      
  2. Grant Type Restrictions:

    • Dynamically enable/disable grants per client via a Compiler Pass or middleware:
      // Example: Restrict to 'authorization_code' only
      $server->setGrantType('authorization_code', true);
      $server->setGrantType('password', false);
      
  3. User Authentication:

    • For user_credentials grant, implement a custom UserAuthenticationProvider:
      use Bshaffer\OAuth2ServerBundle\Provider\UserAuthenticationProviderInterface;
      
      class CustomUserAuth implements UserAuthenticationProviderInterface {
          public function authenticate($username, $password) {
              return User::where('email', $username)->first(); // Adapt to Laravel
          }
      }
      
      Register it in config/oauth2.php:
      'user_authentication_provider' => CustomUserAuth::class,
      
  4. Scopes and Permissions:

    • Use Laravel’s Gate or Policy system to validate scopes:
      // In a middleware or controller
      if (!$server->validateScope('read:data')) {
          throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
      }
      
  5. Token Storage:

    • Store tokens in Laravel’s database (adapt the OAuth2AccessToken model):
      // Example: Extend the model to use Laravel's Eloquent
      class OAuth2AccessToken extends \Bshaffer\OAuth2ServerBundle\Entity\OAuth2AccessToken {
          use \Illuminate\Database\Eloquent\Model;
      }
      

Gotchas and Tips

Common Pitfalls

  1. Symfony-Laravel Integration:

    • Issue: Symfony’s Container vs. Laravel’s ServiceProvider conflicts.
    • Fix: Use Symfony\Bridge\Laravel\ServiceProvider and alias services in config/app.php:
      'aliases' => [
          'oauth2.server' => \Bshaffer\OAuth2ServerBundle\OAuth2Server::class,
      ],
      
  2. Database Schema Mismatch:

    • Issue: The bundle expects specific tables (oauth2_client, oauth2_access_token). Laravel’s migrations may conflict.
    • Fix: Create custom migrations or use Laravel’s schema builder to match the bundle’s requirements:
      Schema::create('oauth2_client', function (Blueprint $table) {
          $table->id();
          $table->string('random_id')->unique();
          $table->string('client_secret');
          $table->string('redirect_uri')->nullable();
          // ... other fields
      });
      
  3. Grant Type Misconfiguration:

    • Issue: Tokens fail with unsupported_grant_type.
    • Fix: Verify config/oauth2.php and ensure the grant type is enabled:
      'grant_types' => ['authorization_code', 'client_credentials'], // Explicitly list allowed grants
      
  4. CSRF Protection:

    • Issue: /token endpoint may block POST requests due to Laravel’s CSRF middleware.
    • Fix: Exclude the route from CSRF protection in app/Http/Middleware/VerifyCsrfToken.php:
      protected $except = [
          'oauth2.token',
      ];
      

Debugging Tips

  1. Enable Verbose Logging:

    • Add to config/oauth2.php:
      'debug' => env('APP_DEBUG', false),
      
    • Check logs for OAuth2-specific errors in storage/logs/laravel.log.
  2. Token Validation:

    • Use the OAuth2 facade to validate tokens in API middleware:
      use Bshaffer\OAuth2ServerBundle\OAuth2;
      
      public function handle($request, Closure $next) {
          $server = OAuth2::server();
          $request->oauth2 = $server->validateAuthenticatedRequest($request);
          return $next($request);
      }
      
  3. Testing with Postman:

    • Use Authorization Code flow:
      1. Request auth URL: GET /authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI.
      2. Exchange code for token: POST /token with grant_type=authorization_code.

Extension Points

  1. Custom Storage:

    • Override OAuth2AccessTokenRepositoryInterface to use Laravel’s Eloquent:
      class EloquentTokenRepository implements OAuth2AccessTokenRepositoryInterface {
          public function getNewToken($clientId, $userId, array $scopes, $grantType) {
              return OAuth2AccessToken::create([...]);
          }
      }
      
      Register it in config/oauth2.php:
      'access_token_repository' => EloquentTokenRepository::class,
      
  2. Custom Responses:

    • Extend OAuth2Response to modify error messages or add custom fields:
      class CustomResponse extends \Bshaffer\OAuth2ServerBundle\Response\OAuth2Response {
          public function setError($error, $errorDescription, array $additionalInformation = []) {
              $additionalInformation['custom_field'] = 'value';
              return parent::setError($error, $errorDescription, $additionalInformation);
          }
      }
      
  3. Event Listeners:

    • Listen to OAuth2 events (e.g., oauth2.token_generated) via Laravel’s events:
      Event::listen('oauth2.token_generated', function ($token) {
          // Log or process token generation
      });
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor