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

alb/oauth2-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this bundle is Symfony2-based, Laravel integration requires a bridge or Symfony components. Use symfony/http-foundation and symfony/dependency-injection for compatibility.

  1. Install Dependencies

    composer require alb/oauth2-server-bundle alb/oauth2-php symfony/http-foundation symfony/dependency-injection
    
  2. Configure Autoloading Add to composer.json:

    "autoload": {
        "psr-4": {
            "Alb\\": "vendor/alb/oauth2-server-bundle/src",
            "OAuth2\\": "vendor/alb/oauth2-php/lib"
        }
    }
    

    Run composer dump-autoload.

  3. Set Up Database Models Create Laravel Eloquent models extending the bundle’s base classes (e.g., OAuth2Client, OAuth2AccessToken):

    // app/Models/OAuth2Client.php
    namespace App\Models;
    use Alb\OAuth2Server\Entity\OAuth2Client as BaseOAuth2Client;
    use Illuminate\Database\Eloquent\Model;
    
    class OAuth2Client extends BaseOAuth2Client implements Model {
        protected $primaryKey = 'id';
        public $timestamps = false;
    }
    
  4. Register Routes Define OAuth2 endpoints in routes/web.php:

    Route::prefix('oauth/v2')->group(function () {
        Route::post('/token', [OAuth2Controller::class, 'token']);
        Route::get('/authorize', [OAuth2Controller::class, 'authorize']);
    });
    
  5. First Use Case: Token Endpoint Implement a controller to handle token requests:

    // app/Http/Controllers/OAuth2Controller.php
    use Alb\OAuth2Server\Server;
    use OAuth2\Storage\PDO as Storage;
    
    class OAuth2Controller extends Controller {
        public function token(Request $request) {
            $server = new Server(
                new Storage(new PDO('mysql:host=...;dbname=...', 'user', 'pass')),
                'http://your-app.test/oauth/v2/authorize'
            );
            $response = $server->handleTokenRequest($request->all());
            return response($response->getBody(), $response->getStatusCode());
        }
    }
    

Implementation Patterns

Workflow: OAuth2 Authorization Code Flow

  1. Client Requests Authorization Redirect users to /oauth/v2/authorize?response_type=code&client_id=.... Use Laravel’s redirect() helper.

  2. User Approval Implement a form in a view (e.g., resources/views/oauth/authorize.blade.php) to confirm scopes.

  3. Exchange Code for Token After approval, call the token endpoint with the auth code:

    $response = Http::post('http://your-app.test/oauth/v2/token', [
        'grant_type' => 'authorization_code',
        'code' => $authCode,
        'redirect_uri' => 'https://client-app.com/callback',
        'client_id' => 'client_id',
        'client_secret' => 'client_secret',
    ]);
    

Integration Tips

  • Laravel Middleware: Protect API routes with OAuth2 validation:
    public function handle($request, Closure $next) {
        $token = $request->bearerToken();
        if (!$token || !$this->validateToken($token)) {
            return response('Unauthorized', 401);
        }
        return $next($request);
    }
    
  • Database Migrations: Use Laravel migrations to create tables for oauth2_client, oauth2_access_token, etc.
  • Custom Storage: Extend OAuth2\Storage\PDO for Laravel’s query builder:
    class LaravelStorage extends PDO {
        public function getClientDetails($client_id) {
            return DB::table('oauth2_client')->where('client_id', $client_id)->first();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony-Specific Assumptions

    • The bundle assumes Symfony’s Request object. Use symfony/http-foundation to bridge Laravel’s Illuminate\Http\Request:
      $symfonyRequest = Request::createFromGlobals();
      
    • Fix: Wrap Laravel requests in Symfony’s Request class before passing to the bundle.
  2. Missing Refresh Token Support The bundle lacks OAuth2RefreshToken model. Implement manually:

    // app/Models/OAuth2RefreshToken.php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model;
    
    class OAuth2RefreshToken extends Model {
        protected $table = 'oauth2_refresh_token';
    }
    
  3. Stateless Firewall Conflicts Laravel’s middleware may conflict with Symfony’s stateless firewall. Disable Laravel’s auth middleware for /oauth/v2 routes.

Debugging

  • Token Validation Errors: Check if the client_id/client_secret match the database.
  • Database Schema Mismatch: Ensure Laravel’s migrations align with the bundle’s expected schema (e.g., id, client_id, user_id fields).

Extension Points

  1. Custom Grant Types Extend the server to support custom grants (e.g., password grant):

    $server->addGrantType(new OAuth2\GrantType\Password($storage));
    
  2. Scope Validation Override checkScope() in a custom storage adapter to enforce Laravel’s policies:

    public function checkScope($client_id, $scope) {
        return Gate::allows('access-scope', [$client_id, $scope]);
    }
    
  3. Token Generation Hooks Use Laravel’s Model::saved() event to log token creation:

    OAuth2AccessToken::saved(function ($token) {
        \Log::info("New token generated: {$token->id}");
    });
    
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