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

Oauth Server Bundle Laravel Package

friendsofsymfony/oauth-server-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require friendsofsymfony/oauth-server-bundle

Add to config/bundles.php (Symfony) or AppKernel.php (legacy):

FriendsOfSymfony\OAuthServerBundle\FOSOAuthServerBundle::class => ['all' => true],
  1. Configuration: Enable the bundle in config/packages/fos_oauth_server.yaml (Symfony 4.4+):

    fos_oauth_server:
        db_driver: orm       # or 'pdo' for PDO-based storage
        client_class:       %fos_oauth_server.model.client.class%
        access_token_class: %fos_oauth_server.model.access_token.class%
        refresh_token_class: %fos_oauth_server.model.refresh_token.class%
        auth_code_class:     %fos_oauth_server.model.auth_code.class%
    
  2. First Use Case:

    • Generate a Client: Use the fos_oauth_server:client:create command:

      php bin/console fos:oauth-server:client:create --random --grant-type=password,refresh_token
      

      Note the client_id and client_secret for API calls.

    • Test OAuth Flow: Use Postman/curl to request a token:

      curl -X POST http://your-app/oauth/v2/token \
           -d "grant_type=password&client_id=YOUR_CLIENT_ID&client_secret=YOUR_SECRET&username=test&password=test"
      

Key Files to Review

  • config/packages/fos_oauth_server.yaml: Core configuration.
  • src/Entity/ (or Resources/config/doctrine/): Doctrine entities for OAuth models (Client, AccessToken, etc.).
  • Resources/doc/index.md: Official documentation for advanced setups.

Implementation Patterns

Common Workflows

1. Client Management

  • Dynamic Client Creation: Extend the ClientManager service to create clients programmatically:

    $clientManager = $this->get('fos_oauth_server.client_manager');
    $client = $clientManager->createClient();
    $client->setRandomId();
    $client->addGrantType('password');
    $clientManager->updateClient($client);
    
  • Client-Specific Logic: Override ClientManager to inject custom logic (e.g., validate client scopes):

    # config/services.yaml
    services:
        App\Service\CustomClientManager:
            decorates: fos_oauth_server.client_manager
            arguments: ['@App\Service\CustomClientManager.inner']
    

2. Token Handling

  • Custom Token Storage: Implement TokenStorageInterface to store tokens in Redis or a custom DB:

    class RedisTokenStorage implements TokenStorageInterface {
        public function findTokenByToken($token) { /* ... */ }
        public function deleteToken($token) { /* ... */ }
    }
    

    Register in config/packages/fos_oauth_server.yaml:

    fos_oauth_server:
        token_storage: App\Service\RedisTokenStorage
    
  • Token Validation Middleware: Use Symfony’s EventSubscriber to validate tokens in controllers:

    class OAuthTokenSubscriber implements EventSubscriber {
        public static function getSubscribedEvents() {
            return [KernelEvents::CONTROLLER => 'onKernelController'];
        }
        public function onKernelController(ControllerEvent $event) {
            $token = $event->getRequest()->headers->get('Authorization');
            if (!$this->isValidToken($token)) {
                throw new AccessDeniedHttpException();
            }
        }
    }
    

3. Grant Type Extensions

  • Custom Grant Types: Create a service implementing GrantTypeInterface:
    class CustomGrantType implements GrantTypeInterface {
        public function getName() { return 'custom'; }
        public function validateGrant($grantData, $client, $user) { /* ... */ }
    }
    
    Register in config/packages/fos_oauth_server.yaml:
    fos_oauth_server:
        grants:
            - custom
    

4. Resource Owner Integration

  • User Provider: Link to your user system (e.g., FOSUserBundle):
    fos_oauth_server:
        user_provider: fos_user.user_provider.username_email
    
    Or create a custom provider:
    class CustomUserProvider implements UserProviderInterface {
        public function loadUserByUsername($username) { /* ... */ }
    }
    

5. API Integration

  • Laravel-Specific Adaptation: Use Symfony’s HttpFoundation components via symfony/http-foundation:
    use Symfony\Component\HttpFoundation\Request;
    $request = Request::createFromGlobals();
    $token = $request->headers->get('Authorization');
    
    Validate tokens in Laravel middleware:
    class OAuthMiddleware {
        public function handle($request, Closure $next) {
            $token = $request->bearerToken();
            if (!$this->validateToken($token)) {
                abort(401);
            }
            return $next($request);
        }
    }
    

Gotchas and Tips

Pitfalls

1. Deprecated Bundle

  • Issue: Last release in 2019; may not support modern Symfony/Laravel features.
    • Workaround: Fork the repo and update dependencies (e.g., Symfony 5/6, Doctrine ORM 2.8+).
    • Alternative: Consider league/oauth2-server (actively maintained).

2. Doctrine ORM Quirks

  • Issue: Default entities assume a specific schema. Custom tables may break migrations.
    • Fix: Override entity classes in config/packages/fos_oauth_server.yaml:
      fos_oauth_server:
          client_class: App\Entity\CustomClient
          access_token_class: App\Entity\CustomAccessToken
      
    • Tip: Use make:entity to scaffold custom entities matching the bundle’s interfaces.

3. Token Storage Conflicts

  • Issue: Token cleanup jobs (e.g., fos_oauth_server:cleanup:tokens) may fail if storage is misconfigured.
    • Debug: Check TokenStorageInterface implementation for deleteToken() logic.
    • Tip: Schedule cleanup via Laravel’s scheduler:
      $schedule->command('fos:oauth-server:cleanup:tokens')->daily();
      

4. Grant Type Validation

  • Issue: Custom grant types may not validate correctly if validateGrant() returns false without throwing an exception.
    • Fix: Throw OAuthServerException for invalid grants:
      throw new OAuthServerException('Invalid grant data');
      

5. CORS and CSRF

  • Issue: Token endpoints may reject requests due to CORS or CSRF protection.
    • Solution: Configure Symfony’s security.yaml to allow OAuth routes:
      security:
          access_control:
              - { path: ^/oauth/v2/token, roles: PUBLIC_ACCESS }
      
    • Laravel: Use VerifyCsrfToken middleware exclusion for /oauth/v2/token.

6. Client Secret Management

  • Issue: Hardcoding client_secret in config or client-side code.
    • Best Practice: Store secrets in Laravel’s .env and fetch via:
      $clientSecret = config('services.oauth.client_secret');
      

Debugging Tips

1. Enable Debug Mode

  • Set debug: true in config/packages/fos_oauth_server.yaml to log OAuth events:
    fos_oauth_server:
        debug: true
    

2. Log Token Requests

  • Add a EventSubscriber to log grant data:
    class OAuthDebugSubscriber implements EventSubscriber {
        public static function getSubscribedEvents() {
            return [OAuthEvents::GRANT_VALIDATED => 'onGrantValidated'];
        }
        public function onGrantValidated(GrantValidatedEvent $event) {
            \Log::info('Grant validated', ['grant' => $event->getGrant()->getName(), 'data' => $event->getGrantData()]);
        }
    }
    

3. Test with Postman

  • Use Postman’s "Authorization" tab to test flows:
    • Password Grant:
      POST /oauth/v2/token
      Headers: Content-Type: application/x-www-form-urlencoded
      Body: grant_type=password&client_id=CLIENT_ID&client_secret=SECRET&username=USER&password=PASS
      

4. Database Schema

  • Verify tables exist after installation:
    php bin/console doctrine:schema:validate
    
    Recreate if needed:
    php bin/console doctrine:schema:update --force
    

Extension Points

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware