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

Http Oauth Laravel Package

dormilich/http-oauth

PSR-compatible OAuth2 Client Credentials extension for dormilich/http-client. Automatically fetches and caches access tokens via a token client/provider, then adds Authorization headers to outgoing requests. Works with PSR-18/17 HTTP clients and PSR-16 cache.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • PSR Compliance: Aligns with PSR-16 (cache), PSR-17 (HTTP factories), and PSR-18 (HTTP client), ensuring compatibility with modern PHP ecosystems (e.g., Laravel, Symfony).
    • Client Credentials Focus: Specialized for backend-to-backend OAuth2 flows (e.g., microservices, CI/CD pipelines), reducing complexity for non-interactive auth.
    • Extensible Design: Supports credential chaining (e.g., domain-based routing) and multiple providers, enabling granular control over auth scopes.
    • Token Refresh Logic: Automatically handles stale/expired tokens (per RFC 6749), reducing manual token management overhead.
  • Cons:

    • Niche Use Case: Limited to Client Credentials (no PKCE, Authorization Code, or Implicit flows), restricting use cases requiring user delegation.
    • No Built-in Persistence: Relies on PSR-16 cache (e.g., SimpleCache), which may require additional setup (e.g., Redis, database) for production-grade token storage.
    • Minimal Adoption: Low stars/dependents suggest unproven stability or community support (risk of undocumented edge cases).

Integration Feasibility

  • Laravel Compatibility:
    • HTTP Layer: Laravel’s GuzzleHttp\Client (PSR-18) and Illuminate\Http\Client can wrap dormilich/http-client, but may require adapter shims for PSR-17 factories.
    • Cache: Laravel’s Illuminate\Cache (PSR-16 compatible) can replace SimpleCache with minimal config.
    • Service Container: Laravel’s DI container can instantiate TokenClient, TokenProvider, and credential providers, reducing boilerplate.
  • Key Dependencies:
    • Guzzle/PsrHttp: If using Laravel’s HTTP client, ensure dormilich/http-client integrates smoothly (may need middleware adapters).
    • Cache Backend: Evaluate Redis/Memcached vs. file-based caching for token persistence.

Technical Risk

  • Token Management:
    • Stale Tokens: RFC 6749 compliance is a plus, but token expiration handling (e.g., jitter, retry logic) may need customization.
    • Rate Limiting: OAuth providers may throttle token requests; implement exponential backoff if needed.
  • Error Handling:
    • Silent Failures: 403/401 responses may not always trigger token refresh (e.g., if the provider returns opaque errors). Add retry logic with circuit breakers.
    • Credential Mismatch: No credentials for a domain = no auth header; ensure fallback behavior aligns with API requirements.
  • Performance:
    • Cache Warmup: Tokens stored in PSR-16 cache may cause cold-start delays. Pre-warm cache or use a faster backend (e.g., Redis).

Key Questions

  1. Use Case Validation:
    • Is Client Credentials the only OAuth flow needed? If not, this package is insufficient.
    • Are there APIs requiring scopes or audience claims? The package lacks explicit scope management.
  2. Token Storage:
    • What’s the preferred cache backend (Redis, database, file)? Does Laravel’s cache need configuration tweaks?
  3. Error Resilience:
    • How should the system handle network failures during token refresh? (e.g., fallback to cached tokens or fail fast?)
  4. Monitoring:
    • Are token refresh rates/logs needed? The package lacks built-in metrics (e.g., Prometheus).
  5. Laravel-Specific:
    • Can dormilich/http-client coexist with Laravel’s HttpClient without conflicts?
    • How will credential providers (e.g., DomainProvider) integrate with Laravel’s routing?

Integration Approach

Stack Fit

  • Laravel Integration Points:
    Component Laravel Equivalent Integration Notes
    PSR-18 HTTP Client GuzzleHttp\Client or HttpClient Use Laravel’s HttpClient facade or wrap Guzzle.
    PSR-17 Factories Symfony\Contracts\HttpClient May need adapter (e.g., GuzzleHttp\Psr7).
    PSR-16 Cache Illuminate\Cache Replace SimpleCache with Cache::store().
    Service Container Laravel’s DI Bind TokenClient, TokenProvider as singletons.
  • Recommended Stack:
    • HTTP: Laravel’s HttpClient (PSR-18) + dormilich/http-client as a middleware layer.
    • Cache: Redis (via Illuminate\Cache) for low-latency token storage.
    • Logging: Laravel’s Log facade to track token refreshes/errors.

Migration Path

  1. Phase 1: Proof of Concept

    • Replace a single API client with dormilich/http-oauth:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(TokenClient::class, fn() => new TokenClient(
              new DefaultProvider(new ClientCredentials(env('CLIENT_ID'), env('CLIENT_SECRET'), env('AUTH_URL'))),
              new GuzzleHttp\Client(),
              new GuzzleHttp\Psr7\HttpFactory(),
              new GuzzleHttp\Psr7\StreamFactory(),
              Cache::store('redis')
          ));
      }
      
    • Test token refresh and request signing with a mock OAuth provider (e.g., OAuth2 Mock Server).
  2. Phase 2: Credential Provider Expansion

    • Implement DomainProvider for multi-API support:
      $domainProvider = new DomainProvider();
      $domainProvider->add($credentials, ['api.example.com', 'api.staging.example.com']);
      $chainProvider = new ChainProvider([$domainProvider, new DefaultProvider($fallbackCredentials)]);
      
    • Bind to Laravel’s container and validate against real API endpoints.
  3. Phase 3: Error Handling & Observability

    • Add middleware to catch 401/403 responses and trigger token refresh:
      // app/Http/Middleware/OAuthRefreshMiddleware.php
      public function handle($request, Closure $next)
      {
          try {
              return $next($request);
          } catch (OAuthException $e) {
              app(TokenProvider::class)->refresh();
              return $next($request);
          }
      }
      
    • Log token refreshes using Laravel’s Log::channel('oauth').

Compatibility

  • Laravel Versions: Tested on Laravel 9+ (PHP 8.0+). Older versions may need PSR-16/PSR-18 polyfills.
  • Guzzle vs. Symfony HTTP Client:
    • Prefer GuzzleHttp\Client for broader compatibility with dormilich/http-client.
    • If using Symfony’s HttpClient, create a PSR-18 adapter (e.g., SymfonyHttpClientAdapter).
  • Cache Backends: All PSR-16 caches work, but Redis is recommended for production.

Sequencing

  1. Prerequisites:
    • Set up Redis/Memcached for token caching.
    • Configure Laravel’s HttpClient or Guzzle for PSR-18 compliance.
  2. Core Integration:
    • Install dormilich/http-oauth and dependencies.
    • Bind TokenClient/TokenProvider to Laravel’s container.
  3. Testing:
    • Unit test credential providers and token refresh logic.
    • Integration test with a real OAuth2 provider (e.g., Auth0, Okta).
  4. Deployment:
    • Roll out to a staging environment with monitoring.
    • Gradually replace hardcoded API clients with the OAuth-enabled client.

Operational Impact

Maintenance

  • Pros:
    • Decoupled Design: Credential providers and token logic are modular; changes to one (e.g., adding a new provider) don’t break others.
    • Laravel Ecosystem: Leverages familiar tools (Redis, Log, DI container), reducing learning curves.
  • Cons:
    • Undocumented Edge Cases: Low adoption may mean hidden bugs (e.g., token refresh races). Plan for:
      • Chaos Testing: Simulate network failures during token refresh.
      • Rollback Plan: Maintain a fallback to manual token management if the package fails.
    • Dependency Updates: dormilich/http-client may lag behind Laravel/Guzzle updates.

Support

  • Debugging:
    • Token Issues: Use Laravel’s Log::debug() to inspect token payloads and cache hits/misses.
    • Credential Mismatches: Add logging to DomainProvider to verify domain matching.
  • Vendor Support:
    • **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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity