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 Xero Laravel Package

calcinai/oauth2-xero

OAuth 2.0 provider for Xero built on the League OAuth2 Client. Supports the authorization code flow, scope configuration, fetching the authenticated user (OpenID) and retrieving authorized Xero tenants for making API requests.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Leverages League OAuth2 Client: Aligns with Laravel’s ecosystem and existing OAuth2 patterns (e.g., Google, GitHub providers), reducing learning curves for developers.
    • Tenant-Aware Design: Critical for accounting/ERP integrations where users manage multiple Xero orgs (e.g., accountants, bookkeepers). The getTenants() method simplifies multi-org access.
    • Scope Granularity: Supports Xero’s scope system (e.g., accounting.transactions, payroll.employees), enabling least-privilege access.
    • Security Features: Built-in PKCE (WIP but promising) and CSRF protection via state tokens reduce attack surfaces for financial data.
    • OpenID Support: Retrieves user identity (openid/profile scopes) without custom endpoints, useful for user provisioning or SSO.
    • MIT License: No vendor lock-in; aligns with open-source-friendly Laravel projects.
  • Cons:

    • No Native Laravel Integration: Requires manual setup (e.g., service providers, facades), though this is offset by flexibility.
    • Token Management: Persistence (e.g., refresh tokens) and rotation must be handled externally, adding boilerplate.
    • PKCE Incomplete: As of v1.3.0, PKCE is marked "WIP," which may require monitoring or custom implementation for production.
    • Limited to Authorization Code Flow: Does not support Client Credentials or other flows, though this covers 90% of web app use cases.

Integration Feasibility

  • Laravel Compatibility:

    • Session Handling: Works seamlessly with Laravel’s session driver (e.g., storing CSRF state in $_SESSION).
    • HTTP Clients: Compatible with Laravel’s Guzzle HTTP client for API calls (e.g., injecting tokens into requests).
    • Authentication: Can integrate with Laravel’s auth system (e.g., map Xero’s openid/profile to Laravel users via custom guards).
    • Events: Supports event-driven architectures (e.g., dispatch XeroTokenRefreshed events for side effects).
  • Dependencies:

    • Primary: league/oauth2-client (v1 or v2) and firebase/php-jwt (v5–7), both stable and Laravel-compatible.
    • PHP Version: Requires PHP 7.1+, which is met by Laravel 5.5+.
    • Database: No schema changes, but requires a table for token storage (e.g., access_token, refresh_token, expires).
  • Xero API Alignment:

    • Abstracts OAuth2 complexity but requires understanding of Xero’s API endpoints for post-authentication calls.
    • Tenant switching logic must be implemented (e.g., routing API calls to the correct tenant ID).

Technical Risk

  • Medium Risk Areas:

    1. Token Management:
      • Refresh tokens expire; requires automated refresh logic (e.g., Laravel queues or cron jobs).
      • Mitigation: Implement a RefreshXeroToken job triggered by token expiration or manual user action.
    2. PKCE Stability:
      • WIP implementation may introduce bugs or incompatibilities.
      • Mitigation: Use feature flags or disable PKCE initially, enabling it once stable.
    3. Xero API Changes:
      • Xero’s OAuth2 endpoints may evolve, requiring package updates.
      • Mitigation: Monitor Xero’s API changelog and test regularly.
    4. Multi-Tenant Complexity:
      • Tenant lists may change frequently, requiring caching strategies.
      • Mitigation: Cache tenant lists in Redis with short TTLs (e.g., 5 minutes).
  • Low Risk Areas:

    • Security: League OAuth2 Client is widely audited; PKCE/CSRF protections are robust.
    • Performance: Minimal overhead for OAuth flows; API calls are the primary bottleneck.

Key Questions

  1. Authentication Flow:

    • Will users authenticate via Xero’s UI (Authorization Code) or silently (e.g., embedded app)? This dictates PKCE vs. traditional flow.
    • Example: For SPAs or mobile apps, enable PKCE; for server-side apps, traditional flow may suffice.
  2. Token Storage:

    • How will tokens be persisted? Options:
      • Encrypted database (e.g., oauth_access_tokens table with user_id, tenant_id, token, expires_at).
      • Laravel cache (e.g., cache:forever for short-lived tokens).
      • Redis (for distributed caching).
    • Example: Use Laravel’s encrypt() for sensitive fields like refresh_token.
  3. Multi-Tenant Routing:

    • How will the app route API calls to the correct Xero tenant?
      • Option 1: Tenant ID in URL (e.g., /xero/{tenantId}/invoices).
      • Option 2: User-selected tenant (e.g., dropdown in UI).
      • Option 3: Default tenant per user.
    • Example: Store tenant_id in the user model and inject it into API calls.
  4. Error Handling:

    • How will failed OAuth flows (e.g., revoked tokens, expired scopes) be handled?
      • Redirect users to a reconnect flow (e.g., "Your Xero access expired. [Reconnect]").
      • Log errors for debugging (e.g., Sentry or Laravel logs).
    • Example: Create a XeroAuthException handler with user-friendly messages.
  5. Performance Optimization:

    • Will tenant lists be cached? How often do they change?
      • Example: Cache tenants in Redis with a 5-minute TTL and invalidate on token refresh.
    • Will API calls be batched or queued for async processing?
      • Example: Use Laravel Horizon to queue Xero API calls during off-peak hours.
  6. Compliance and Auditing:

    • Does the app need to log OAuth interactions for compliance?
      • Example: Log XeroTokenRefreshed events with metadata (user ID, tenant ID, scopes).
    • Are there regulatory requirements for token storage (e.g., GDPR, SOC 2)?
      • Example: Encrypt tokens at rest and in transit.
  7. Testing Strategy:

    • How will OAuth flows be tested?
    • Will mock providers be used for unit tests?
      • Example: Extend the provider for testing (e.g., mock getAccessToken()).

Integration Approach

Stack Fit

  • Laravel-Specific Components:

    • Service Container: Bind the Xero provider as a singleton or context-based binding for dependency injection.
      $this->app->singleton(XeroProvider::class, function ($app) {
          return new \Calcinai\OAuth2\Client\Provider\Xero([
              'clientId' => config('services.xero.client_id'),
              'clientSecret' => config('services.xero.client_secret'),
              'redirectUri' => config('services.xero.redirect_uri'),
          ]);
      });
      
    • Middleware: Create middleware to validate Xero tokens on protected routes.
      namespace App\Http\Middleware;
      
      use Closure;
      use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
      
      class ValidateXeroToken
      {
          public function handle($request, Closure $next)
          {
              try {
                  $token = $request->user()->xeroToken;
                  $provider = app(XeroProvider::class);
                  $provider->getResourceOwner($token);
              } catch (IdentityProviderException $e) {
                  return redirect()->route('xero.reconnect');
              }
              return $next($request);
          }
      }
      
    • Events: Dispatch events for token refreshes or API call failures.
      event(new XeroTokenRefreshed($user, $newToken));
      
    • Artisan Commands: Add commands for testing OAuth flows.
      php artisan xero:auth --tenant=123
      
    • Facades: Create a Xero facade for cleaner syntax.
      use App\Facades\Xero;
      
      $tenants = Xero::getTenants();
      
  • Third-Party Tools:

    • Guzzle HTTP Client: Use alongside the package for API calls (e.g., inject tokens into requests).
      $client = new \GuzzleHttp\Client();
      $response = $client->request('GET', 'https://api.xero.com/api.xro/2.0/Invoices', [
          'headers' => [
              'Authorization' => 'Bearer ' . $token->getToken(),
          ],
      ]);
      
    • Laravel Horizon: Queue token refreshes or API calls for async processing.
      RefreshXeroToken::dispatch($user)->delay(now()->addMinutes(30
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor