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

Cpjoauth Server Bundle Laravel Package

cpj/cpjoauth-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this is a Symfony bundle, direct Laravel integration requires Symfony Bridge or a wrapper. Use symfony/bridge or laravel/symfony-finder for compatibility.

  1. Install via Composer (Symfony-only, but adaptable):

    composer require cpj/cpjFOSOAuthServerBundle
    

    For Laravel, create a custom wrapper or use a Symfony microkernel (e.g., symfony/console).

  2. First Use Case: OAuth2 Authorization Server

    • Configure routes in config/routes.yaml (Symfony) or Laravel’s routes/web.php (via a Symfony component proxy).
    • Example route:
      # Symfony
      fos_oauth_server_token:
          resource: "@FOSOAuthServerBundle/Resources/config/routing/token.xml"
          prefix: /oauth/v2
      
    • In Laravel, proxy this via a controller:
      Route::get('/oauth/v2/token', [OAuthController::class, 'token']);
      
  3. Key Files to Review

    • Resources/doc/index.md (official docs).
    • Resources/config/routing/token.xml (endpoint definitions).
    • DependencyInjection/Configuration.php (bundle config).

Implementation Patterns

Workflow: Building an OAuth2 Server in Laravel

  1. Symfony-Laravel Bridge

    • Use spatie/symfony-laravel to embed Symfony components.
    • Example: Load the bundle in a Laravel service provider:
      use Symfony\Component\HttpKernel\Kernel;
      use Cpj\FOSOAuthServerBundle\CpjFOSOAuthServerBundle;
      
      class OAuthServiceProvider extends ServiceProvider {
          public function register() {
              $kernel = new Kernel(env('APP_ENV'), false);
              $kernel->boot();
              $kernel->getContainer()->register(new CpjFOSOAuthServerBundle(), true);
          }
      }
      
  2. Client & Grant Management

    • Register Clients via Symfony’s fos_oauth_server.client service or a Laravel facade:
      // Symfony (adapt to Laravel)
      $clientManager = $this->get('fos_oauth_server.client_manager');
      $client = $clientManager->createClient();
      $client->setRandomId();
      $client->setSecret('secret');
      $clientManager->updateClient($client);
      
    • Grant Types: Support authorization_code, password, or client_credentials via config:
      # config/packages/fos_oauth_server.yaml (Symfony)
      fos_oauth_server:
          grants:
              - authorization_code
              - password
      
  3. Token Generation & Validation

    • Use the fos_oauth_server.token_storage service to issue/validate tokens:
      $tokenStorage = $this->get('fos_oauth_server.token_storage');
      $token = $tokenStorage->createAccessToken($client, $user, ['scope' => 'read']);
      
    • In Laravel, wrap this in a trait or helper:
      trait OAuthHelper {
          public function issueToken(User $user, Client $client) {
              return app('fos_oauth_server.token_storage')->createAccessToken($client, $user, ['scope' => 'read']);
          }
      }
      
  4. Resource Server Integration

    • Protect Laravel routes with OAuth2 validation:
      Route::get('/api/data', function () {
          $token = request()->bearerToken();
          $validator = $this->get('fos_oauth_server.token_validator');
          if (!$validator->validateToken($token)) {
              abort(401);
          }
          return response()->json(['data' => 'protected']);
      })->middleware('auth:api');
      

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Hell

    • The bundle assumes Symfony’s HttpFoundation, Security, and DependencyInjection. In Laravel:
      • Use symfony/http-foundation for request/response objects.
      • Mock SecurityContext with Laravel’s Auth facade:
        $security = new SymfonySecurityContext(app('auth')->user());
        $this->get('fos_oauth_server.security.token_storage')->setToken($security->getToken());
        
  2. Token Storage Backend

    • Defaults to session storage (Symfony). For Laravel, switch to a database or Redis:
      # config/packages/fos_oauth_server.yaml
      fos_oauth_server:
          token_storage:
              class: Cpj\FOSOAuthServerBundle\Storage\DoctrineOAuthTokenStorage
              entity: App\Entity\OAuthToken
      
    • Create a custom storage class extending OAuthTokenStorageInterface.
  3. CSRF & State Management

    • Symfony’s fos_oauth_server.authorization uses CSRF tokens. In Laravel:
      • Disable CSRF for OAuth endpoints or implement manually:
        Route::post('/oauth/v2/auth', function () {
            if (!hash_equals(session('oauth_state'), request('state'))) {
                abort(403);
            }
            // Proceed with auth.
        });
        
  4. CORS Headers

    • Laravel’s CORS middleware may conflict with Symfony’s OAuth2Response. Configure CORS explicitly:
      Header::set('Access-Control-Allow-Origin', '*');
      Header::set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/monolog.yaml (Symfony) or Laravel’s config/logging.php:

    handlers:
        oauth:
            type: stream
            path: "%kernel.logs_dir%/oauth.log"
            level: debug
    
  2. Token Validation Errors Common issues:

    • invalid_grant: Check client credentials or grant type.
    • invalid_scope: Verify scopes in fos_oauth_server.scopes config.
    • expired_token: Ensure token TTL is set in storage backend.
  3. Database Schema Mismatch Run Symfony’s migrations (adapted for Laravel):

    php bin/console doctrine:migrations:execute --query="CREATE TABLE oauth_token (id INT AUTO_INCREMENT PRIMARY KEY, ...)"
    

Extension Points

  1. Custom Grant Types Extend OAuthGrantType:

    class CustomGrant extends AbstractGrant {
        public function getName() { return 'custom_grant'; }
        protected function validateGrant($grant) { /* ... */ }
    }
    

    Register in config:

    fos_oauth_server:
        grants:
            - custom_grant
    
  2. User Provider Integration Override Symfony’s UserProvider to use Laravel’s User model:

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

    Bind in services:

    services:
        fos_oauth_server.user_provider:
            class: App\Service\LaravelUserProvider
    
  3. API Rate Limiting Combine with Laravel’s throttle middleware:

    Route::middleware(['throttle:60,1', 'oauth'])->get('/api/rate-limited');
    
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