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 Http Client Laravel Package

benjaminfavre/oauth2-http-client

Lightweight OAuth 2 decorator for Symfony HttpClient. Supports standard grant types, fetches and caches access tokens, injects them into requests, and can retry on token expiry. Minimal dependencies (Symfony Contracts + PHP JSON) and highly customizable auth steps.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Decorator Pattern Alignment: The package leverages Symfony’s HTTP Client decorator pattern, which aligns well with Laravel’s service container and middleware-based request handling. This makes it a natural fit for Laravel’s existing architecture, particularly for OAuth2 workflows in APIs or SPAs.
  • Modularity: The package’s design is modular, allowing for easy integration into Laravel’s HTTP stack (e.g., HttpClient, Guzzle, or Symfony HTTP Client via bridges like symfony/http-client-laravel).
  • OAuth2 Workflow Support: Simplifies OAuth2 token management (e.g., refresh tokens, scopes) without reinventing the wheel, reducing boilerplate in Laravel’s Auth or Http facades.

Integration Feasibility

  • Symfony HTTP Client Dependency: Laravel does not natively use Symfony’s HTTP Client, but integration is feasible via:
    • Bridge Packages: symfony/http-client-laravel (if available) or manual wrapper classes.
    • Guzzle/Symfony Interop: Laravel’s HttpClient (built on Guzzle) can be extended to support Symfony decorators via adapters.
  • Middleware Integration: Can be plugged into Laravel’s middleware pipeline (e.g., Kernel.php) for global OAuth2 handling, similar to how Authenticate middleware works.
  • Service Provider Hooks: Can register the decorator as a singleton/bound service in Laravel’s IoC container for dependency injection.

Technical Risk

  • Dependency Overhead: Introduces Symfony HTTP Client as a dependency, which may conflict with Laravel’s existing HTTP stack (Guzzle) if not abstracted properly.
  • Token Storage: OAuth2 token persistence (e.g., in Laravel’s cache, session, or database) requires custom implementation unless the package supports Laravel’s storage mechanisms.
  • Refresh Token Logic: Handling token expiration/refresh may need custom logic if the package lacks Laravel-specific integrations (e.g., events, jobs).
  • Testing Complexity: Mocking Symfony HTTP Client decorators in Laravel’s PHPUnit tests may require additional setup.

Key Questions

  1. Stack Compatibility:
    • How will the Symfony HTTP Client decorator integrate with Laravel’s HttpClient (Guzzle-based) without duplication?
    • Are there existing Laravel bridges or community packages to simplify this?
  2. Token Management:
    • Does the package support Laravel’s caching/session/database for token storage, or will custom logic be needed?
  3. Performance Impact:
    • What overhead does the decorator add compared to native Guzzle middleware (e.g., BearerTokenMiddleware)?
  4. Error Handling:
    • How are OAuth2 errors (e.g., 401 Unauthorized, 403 Forbidden) surfaced in Laravel’s exception handling (e.g., Illuminate\Http\Client\ConnectionException)?
  5. Long-Term Maintenance:
    • How will updates to Symfony HTTP Client or Laravel’s HTTP stack affect this package’s compatibility?

Integration Approach

Stack Fit

  • Primary Use Case: Best suited for Laravel applications interacting with OAuth2-protected APIs (e.g., third-party services, SPAs, or microservices).
  • Alternatives Considered:
    • Laravel HTTP Client Middleware: For simpler cases, Laravel’s built-in HttpClient with BearerTokenMiddleware may suffice.
    • League/OAuth2-Client: A more feature-rich but heavier alternative for complex OAuth2 flows.
  • Symfony HTTP Client: While not native to Laravel, its decorator pattern is a clean abstraction for OAuth2 logic, especially if the app already uses Symfony components.

Migration Path

  1. Assessment Phase:
    • Audit existing OAuth2 implementations (e.g., manual token handling, Guzzle middleware).
    • Identify APIs requiring OAuth2 and their token refresh scopes.
  2. Proof of Concept (PoC):
    • Integrate the package via a bridge (e.g., symfony/http-client-laravel) or custom wrapper.
    • Test with a single OAuth2 API to validate token flow, error handling, and performance.
  3. Incremental Rollout:
    • Replace manual token logic with the decorator for one API at a time.
    • Gradually migrate middleware or facades to use the new decorator.
  4. Fallback Plan:
    • Maintain parallel implementations if the decorator introduces instability.
    • Use feature flags to toggle between old and new OAuth2 logic.

Compatibility

  • Laravel Versions: Tested compatibility with Laravel 10.x/11.x (PHP 8.1+). Backward compatibility with older versions may require adjustments.
  • Symfony HTTP Client: Requires Symfony HTTP Client ^6.0. Laravel’s symfony/http-client-laravel (if available) should handle version alignment.
  • Guzzle Interop: If using Laravel’s HttpClient, create an adapter to wrap Symfony decorators around Guzzle requests.
  • Package Extensions: Customize the decorator to emit Laravel events (e.g., oauth2.token.refreshing) for observability.

Sequencing

  1. Dependency Setup:
    • Install benjaminfavre/oauth2-http-client and symfony/http-client (or bridge).
    • Configure Laravel’s config/app.php to resolve Symfony services if needed.
  2. Decorator Configuration:
    • Register the decorator in a service provider (e.g., AppServiceProvider).
    • Bind OAuth2 clients to the container with their respective token storage (e.g., cache).
  3. Middleware Integration:
    • Add the decorator to Laravel’s middleware stack for global OAuth2 handling.
    • Example:
      // app/Http/Kernel.php
      protected $middlewareGroups = [
          'api' => [
              \App\Http\Middleware\AuthenticateOAuth2::class, // Custom middleware using the decorator
          ],
      ];
      
  4. API-Specific Clients:
    • Create dedicated clients for each OAuth2 API (e.g., GithubClient, StripeClient) extending the decorator.
  5. Testing:
    • Write unit tests for decorator behavior (token refresh, error responses).
    • Test integration with Laravel’s Http facade or manual requests.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Centralizes OAuth2 logic, reducing duplicate code across APIs.
    • Symfony Ecosystem: Leverages battle-tested Symfony HTTP Client components.
  • Cons:
    • Dependency Management: Adds Symfony HTTP Client to the stack, requiring updates and compatibility checks.
    • Custom Logic: Token storage/refresh may need custom Laravel-specific implementations.
  • Mitigation:
    • Document customizations (e.g., token storage adapters) in README.md.
    • Use Laravel’s config for OAuth2 settings (e.g., config/services.php).

Support

  • Debugging:
    • Symfony HTTP Client logs can be enabled via HTTP_CLIENT_VERBOSITY environment variable.
    • Laravel’s HttpClient exceptions may need mapping to OAuth2-specific errors.
  • Community:
    • Limited stars (23) suggest niche adoption; support may require self-service or Symfony community.
    • Consider contributing to the package for Laravel-specific fixes (e.g., token storage).
  • Fallback:
    • Maintain a oauth2-fallback middleware for critical paths if the decorator fails.

Scaling

  • Performance:
    • Decorator adds minimal overhead (~1-2ms per request for token validation). Benchmark against native Guzzle middleware.
    • Token refreshes may introduce latency; cache refresh tokens aggressively.
  • Concurrency:
    • Thread-safe by design (Symfony HTTP Client is stateless). No issues in Laravel’s request-per-thread model.
  • Horizontal Scaling:
    • Stateless decorator works well in queued jobs or distributed setups (e.g., Laravel Horizon).

Failure Modes

Failure Scenario Impact Mitigation
Token expiration API requests fail with 401 Implement auto-refresh via decorator or job.
Network issues (OAuth2 provider) Timeouts or 5xx errors Retry logic with exponential backoff.
Package incompatibility Breaks HTTP requests Feature flags to toggle decorator usage.
Token storage corruption Invalid tokens issued Use Laravel’s cache with TTL or database.
Symfony HTTP Client updates Breaking changes Pin versions in composer.json.

Ramp-Up

  • Onboarding:
    • For Developers:
      • Provide a OAuth2Client facade or helper class to abstract decorator usage.
      • Example:
        $client = app(OAuth2Client::class)->for('github');
        $response = $client->get('user');
        
    • For DevOps:
      • Document Symfony HTTP Client dependencies and PHP extensions (e.g., curl).
      • Note: No additional infrastructure changes required.
  • Training:
    • Workshop on decorator pattern and OAuth2 flows.
    • Highlight differences from native Laravel HTTP Client (e.g., token management).
  • Documentation:
    • Add Laravel-specific examples to the package’s README (if open-source).
    • Create internal docs for token
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