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

authbucket/oauth2-symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel (Symfony Bundle Adaptation)

Since this is a Symfony bundle, Laravel integration requires Symfony Bridge or a Microkernel approach. Start with:

  1. Install Dependencies

    composer require authbucket/oauth2-symfony-bundle symfony/framework-bundle symfony/security-bundle symfony/monolog-bundle
    
  2. Configure Kernel (Laravel 8+ with Symfony Components) Create a Kernel.php in app/Kernel.php:

    use Symfony\Component\HttpKernel\Kernel as BaseKernel;
    use AuthBucket\Bundle\OAuth2Bundle\AuthBucketOAuth2Bundle;
    
    class Kernel extends BaseKernel {
        public function registerBundles() {
            return [
                new FrameworkBundle(),
                new SecurityBundle(),
                new MonologBundle(),
                new AuthBucketOAuth2Bundle(),
            ];
        }
    }
    
  3. Register Routes Add to routes/web.php:

    use Symfony\Component\Routing\Loader\YamlFileLoader;
    use Symfony\Component\Routing\RouteCollection;
    
    $loader = new YamlFileLoader();
    $routes = $loader->load(__DIR__.'/config/routing.yml');
    

    Create config/routing.yml:

    authbucketoauth2bundle:
        prefix: /api/oauth2
        resource: "@AuthBucketOAuth2Bundle/Resources/config/routing.yml"
    
  4. Basic Security Configuration In config/packages/security.yaml:

    firewalls:
        api_oauth2_authorize:
            pattern: ^/api/oauth2/authorize$
            http_basic: ~
        api_oauth2_token:
            pattern: ^/api/oauth2/token$
            oauth2_token: ~
        api_oauth2_debug:
            pattern: ^/api/oauth2/debug$
            oauth2_resource: ~
    
  5. First Use Case: Password Grant Flow Test the /api/oauth2/token endpoint with:

    curl -X POST -u "demousername1:demopassword1" \
      -d "grant_type=password&username=demousername1&password=demopassword1" \
      http://localhost/api/oauth2/token
    

Implementation Patterns

1. OAuth2 Endpoint Workflows

Authorization Code Flow (Recommended for SPAs)

  • Frontend (SPA/Client): Redirect user to /api/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI.
  • Backend (Symfony):
    • Protect /authorize with http_basic or custom firewall.
    • Use authbucket_oauth2.authorization_controller to handle the OAuth2 flow.
    • Redirect back with code parameter.

Token Exchange (Resource Server)

  • Client Request: Exchange code for access_token at /api/oauth2/token:
    curl -X POST -u "CLIENT_ID:CLIENT_SECRET" \
      -d "grant_type=authorization_code&code=AUTH_CODE&redirect_uri=REDIRECT_URI" \
      http://localhost/api/oauth2/token
    

Resource Protection

  • Protected API Endpoint:
    # config/security.yaml
    firewalls:
        api_resource:
            pattern: ^/api/protected
            oauth2_resource:
                scope: [read, write]
    
    • Laravel: Use middleware to validate the Authorization: Bearer <token> header.

2. Custom User Provider Integration

For password grant type, override the user_provider in config/packages/authbucket_oauth2.yaml:

authbucket_oauth2:
    user_provider: App\Security\UserProvider  # Must implement UserProviderInterface

Example UserProvider:

use AuthBucket\OAuth2\Storage\UserProviderInterface;
use App\Models\User;

class UserProvider implements UserProviderInterface {
    public function getUserByUsername($username) {
        return User::where('username', $username)->first();
    }
}

3. Doctrine ORM Integration

Enable ORM storage in config/packages/authbucket_oauth2.yaml:

authbucket_oauth2:
    driver: orm
    model:
        access_token: App\Entity\AccessToken
        authorization_code: App\Entity\AuthorizationCode
        client: App\Entity\Client
        refresh_token: App\Entity\RefreshToken
        scope: App\Entity\Scope

Generate Entities:

php bin/console doctrine:generate:entity AuthBucket\OAuth2\Entity

4. Custom Scopes and Claims

Extend the Scope entity or use the debug_controller to inspect token claims:

// In a controller
$debugController = $this->get('authbucket_oauth2.debug_controller');
$token = $debugController->debugToken($accessToken);

Gotchas and Tips

1. Laravel-Specific Pitfalls

  • Symfony Kernel Conflict: Avoid mixing Symfony’s Kernel with Laravel’s service container. Use Symfony’s DI or Laravel’s Symfony Bridge (spatie/laravel-symfony). Fix: Isolate the bundle in a microkernel or use a service provider wrapper.

  • Route Prefix Collisions: Ensure /api/oauth2 doesn’t conflict with Laravel’s default routes. Use:

    Route::prefix('api/oauth2')->group(function () {
        // Symfony routes here
    });
    

2. Configuration Quirks

  • In-Memory vs. ORM Storage: Defaults to in_memory, which is not persistent. Switch to orm for production:

    authbucket_oauth2:
        driver: orm
    

    Warning: Migrate existing tokens manually if switching drivers.

  • CORS Issues: The /authorize endpoint may fail with CORS if not configured. Add to config/cors.php:

    'paths' => ['/api/oauth2/authorize'],
    'allowed_methods' => ['GET'],
    

3. Debugging and Logging

  • Enable Debug Mode:

    # config/packages/monolog.yaml
    handlers:
        oauth2:
            type: stream
            path: "%kernel.logs_dir%/oauth2.log"
            level: debug
    

    Log OAuth2 Events:

    $this->get('authbucket_oauth2.logger')->debug('Custom event', ['data' => $data]);
    
  • Token Debugging: Use the built-in /debug endpoint to inspect tokens:

    curl -H "Authorization: Bearer $TOKEN" http://localhost/api/oauth2/debug
    

4. Extension Points

  • Custom Grant Types: Extend AuthBucket\OAuth2\GrantType\AbstractGrantType and register in services.yaml:

    services:
        App\Grant\CustomGrant:
            tags: [authbucket_oauth2.grant_type]
    
  • Token Validation Middleware (Laravel): Create middleware to validate tokens before hitting protected routes:

    use AuthBucket\OAuth2\Token\AccessToken;
    
    class OAuth2Middleware {
        public function handle($request, Closure $next) {
            $token = $this->getTokenFromHeader($request);
            if (!$token->validate()) {
                abort(401);
            }
            return $next($request);
        }
    }
    

5. Performance Tips

  • Cache Remote Debug Endpoints: Configure caching for remote token validation:
    authbucket_oauth2:
        resource_server:
            debug_endpoint: https://remote-server/oauth2/debug
            cache: true
    
  • Batch Scope Checks: For high-traffic APIs, preload scopes in memory:
    $this->get('authbucket_oauth2.scope_manager')->loadScopes(['read', 'write']);
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle