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

cleverage/oauth-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cleverage/oauth-api-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Cleverage\OAuthApiBundle\CleverageOAuthApiBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console cleverage:oauth-api:install
    

    Update config/packages/cleverage_oauth_api.yaml with your OAuth provider details (e.g., client ID, secret, token URL).

  3. First Use Case: Fetching OAuth Tokens Inject the OAuthApiClient service and authenticate:

    use Cleverage\OAuthApiBundle\Client\OAuthApiClient;
    
    public function __construct(private OAuthApiClient $oauthClient) {}
    
    public function getAccessToken()
    {
        $token = $this->oauthClient->getAccessToken(
            'client_credentials', // grant type
            ['scope' => 'read write']
        );
        return $token->getToken();
    }
    

Implementation Patterns

Core Workflows

  1. Token Management

    • Refresh Tokens: Use getAccessToken() with a refresh token:
      $token = $this->oauthClient->getAccessToken(
          'refresh_token',
          ['refresh_token' => $storedRefreshToken]
      );
      
    • Store Tokens Securely: Leverage Symfony’s security.token_storage or a custom service to persist tokens (e.g., in the database or cache).
  2. API Requests

    • Authenticated Requests: Attach the token to requests via middleware or the client:
      $response = $this->oauthClient->request(
          'GET',
          'https://api.example.com/data',
          ['headers' => ['Authorization' => 'Bearer ' . $token]]
      );
      
    • Rate Limiting: Handle 429 Too Many Requests by implementing exponential backoff in your service layer.
  3. Event-Driven Extensions

    • Subscribe to oauth_api.token.refresh events to automate token refreshes:
      // src/EventListener/OAuthTokenListener.php
      public function onTokenRefresh(TokenRefreshEvent $event) {
          $event->setToken($this->generateNewToken());
      }
      
      Register in services.yaml:
      services:
          App\EventListener\OAuthTokenListener:
              tags:
                  - { name: kernel.event_listener, event: oauth_api.token.refresh }
      
  4. Provider-Specific Configs

    • Override provider configs per environment (e.g., config/packages/dev/cleverage_oauth_api.yaml):
      cleverage_oauth_api:
          providers:
              google:
                  client_id: "%env(GOOGLE_CLIENT_ID_DEV)%"
                  client_secret: "%env(GOOGLE_CLIENT_SECRET_DEV)%"
      

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • Issue: Silent failures if tokens expire without refresh logic.
    • Fix: Implement a decorator around OAuthApiClient to auto-refresh tokens:
      class AutoRefreshOAuthClient implements OAuthApiClientInterface {
          public function request(string $method, string $url, array $options = []): ResponseInterface {
              if ($this->isTokenExpired()) {
                  $this->refreshToken();
              }
              return $this->decorated->request($method, $url, $options);
          }
      }
      
  2. Provider-Specific Quirks

    • PKCE for Public Clients: The bundle doesn’t natively support PKCE (Proof Key for Code Exchange). For public clients (e.g., SPAs), use a library like league/oauth2-client alongside this bundle.
    • Custom Grant Types: Extend Cleverage\OAuthApiBundle\Client\OAuthApiClient to support non-standard grants (e.g., urn:ietf:params:oauth:grant-type:saml2-bearer).
  3. Configuration Overrides

    • Issue: Changes to cleverage_oauth_api.yaml may not reflect without clearing the cache:
      php bin/console cache:clear
      
  4. Debugging Token Issues

    • Enable debug mode in config/packages/dev/cleverage_oauth_api.yaml:
      cleverage_oauth_api:
          debug: true
      
    • Check logs for oauth_api channel errors (e.g., monolog configuration).

Tips

  1. Testing

    • Use vcr or mockery to record/stub OAuth responses:
      $mockClient = Mockery::mock(OAuthApiClient::class);
      $mockClient->shouldReceive('getAccessToken')
          ->andReturn(new Token('mock_token', new \DateTime('+1 hour')));
      
  2. Performance

    • Cache tokens in Redis or APCu with a short TTL (e.g., 5 minutes before expiry):
      $cache = $container->get('cache.app');
      $token = $cache->get('oauth_token', function() {
          return $this->oauthClient->getAccessToken('client_credentials');
      });
      
  3. Security

    • Never hardcode secrets. Use Symfony’s %env() or a secrets manager (e.g., symfony/secret).
    • Restrict token scopes to the minimum required for your API calls.
  4. Extending Functionality

    • Custom Providers: Create a new class extending Cleverage\OAuthApiBundle\Provider\AbstractProvider for unsupported providers.
    • Request Interceptors: Add middleware to log requests/responses:
      $this->oauthClient->addInterceptor(function (RequestInterface $request) {
          $request->setHeader('X-Custom-Header', 'value');
      });
      
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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