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

2lenet/oauth-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require 2lenet/oauth-client-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        TwoLenet\OAuthClientBundle\TwoLenetOAuthClientBundle::class => ['all' => true],
    ];
    
  2. Configuration

    • The bundle requires internal 2le Connect documentation (link).
    • Copy config/packages/two_lenet_oauth_client.yaml.dist to config/packages/two_lenet_oauth_client.yaml and update:
      two_lenet_oauth_client:
          client_id: '%env(OAUTH_CLIENT_ID)%'
          client_secret: '%env(OAUTH_CLIENT_SECRET)%'
          redirect_uri: '%env(OAUTH_REDIRECT_URI)%'
          base_url: 'https://connect.2le.net'  # Default; override if needed
      
  3. First Use Case: Authentication Flow

    • Generate an OAuth URL in a controller:
      use TwoLenet\OAuthClientBundle\Service\OAuthService;
      
      public function authenticate(OAuthService $oauthService)
      {
          $authUrl = $oauthService->getAuthorizationUrl(['scope' => 'read write']);
          return redirect($authUrl);
      }
      
    • Handle the callback:
      public function callback(OAuthService $oauthService, Request $request)
      {
          $token = $oauthService->handleAuthorizationCallback($request);
          // Store $token->getAccessToken() securely (e.g., session/DB)
      }
      

Implementation Patterns

Workflows

  1. Token Management

    • Refresh Tokens: Use OAuthService::refreshAccessToken($refreshToken).
    • Store Tokens: Save tokens in a user model or session:
      $user->accessToken = $token->getAccessToken();
      $user->refreshToken = $token->getRefreshToken();
      $user->tokenExpiresAt = $token->getExpiresAt();
      $user->save();
      
  2. API Integration

    • Attach tokens to HTTP clients (e.g., Guzzle):
      $client = new Client([
          'headers' => [
              'Authorization' => 'Bearer ' . $user->accessToken,
          ],
      ]);
      
  3. Scopes and Permissions

    • Request granular scopes during auth:
      $authUrl = $oauthService->getAuthorizationUrl(['scope' => 'scope1 scope2']);
      
    • Validate scopes on the server side (2le Connect’s API will enforce this).
  4. Middleware for Protected Routes

    • Create middleware to verify tokens:
      use TwoLenet\OAuthClientBundle\Service\TokenValidator;
      
      public function handle(Request $request, Closure $next, TokenValidator $validator)
      {
          if (!$validator->validate($request->bearerToken())) {
              abort(401);
          }
          return $next($request);
      }
      

Integration Tips

  • Environment Variables: Use .env for sensitive data:
    OAUTH_CLIENT_ID=your_client_id
    OAUTH_CLIENT_SECRET=your_secret
    OAUTH_REDIRECT_URI=https://your-app.com/oauth/callback
    
  • State Parameter: Add CSRF protection to auth URLs:
    $authUrl = $oauthService->getAuthorizationUrl([
        'scope' => 'read',
        'state' => bin2hex(random_bytes(32)),
    ]);
    
  • Logging: Enable debug mode in config/packages/two_lenet_oauth_client.yaml:
    debug: true
    
    Logs will appear in var/log/dev.log.

Gotchas and Tips

Pitfalls

  1. Internal Documentation Dependency

    • The bundle assumes familiarity with 2le Connect’s client docs.
    • Fix: Bookmark the docs and test endpoints locally before production.
  2. Token Expiry Handling

    • Tokens expire silently. Implement a token refresh interceptor:
      if ($token->hasExpired()) {
          $token = $oauthService->refreshAccessToken($user->refreshToken);
          $user->update(['accessToken' => $token->getAccessToken()]);
      }
      
  3. Redirect URI Mismatch

    • The redirect_uri in the bundle must match the one registered in 2le Connect.
    • Debug: Check the callback URL in logs if redirects fail.
  4. Scope Validation

    • 2le Connect’s API rejects requests with invalid scopes. Validate scopes client-side before making API calls.

Debugging

  • Enable Debug Mode: Set debug: true in config to log OAuth responses.
  • Test with Postman:
    • Manually construct requests to verify endpoints:
      POST https://connect.2le.net/oauth/token
      Headers: Content-Type: application/x-www-form-urlencoded
      Body: grant_type=authorization_code&code={CODE}&redirect_uri={URI}
      
  • Common Errors:
    • invalid_grant: Expired code or refresh token.
    • redirect_uri_mismatch: Callback URL doesn’t match registration.

Extension Points

  1. Custom Token Storage

    • Override TwoLenet\OAuthClientBundle\Service\TokenStorageInterface to use a custom storage backend (e.g., Redis).
  2. Event Listeners

    • Extend the bundle by subscribing to events (e.g., oauth.token.refresh):
      // config/services.yaml
      TwoLenet\OAuthClientBundle\EventListener\TokenRefreshListener:
          tags:
              - { name: kernel.event_listener, event: oauth.token.refresh, method: onTokenRefresh }
      
  3. Custom Grant Types

    • The bundle supports authorization_code by default. For other grants (e.g., client_credentials), extend OAuthService:
      $token = $oauthService->getToken('client_credentials', [
          'client_id' => $clientId,
          'client_secret' => $clientSecret,
      ]);
      
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.
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
spatie/laravel-javascript-views