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

awuniversity/oauth2-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require awuniversity/oauth2-client
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="AWUniversity\OAuth2Client\OAuth2ClientServiceProvider"
    
  2. Configuration Edit config/oauth2-client.php with your OAuth provider details (e.g., client ID, secret, redirect URI). Example for a generic OAuth2 provider:

    'providers' => [
        'generic' => [
            'client_id' => env('OAUTH_CLIENT_ID'),
            'client_secret' => env('OAUTH_CLIENT_SECRET'),
            'redirect' => env('OAUTH_REDIRECT_URI'),
            'scope' => ['openid', 'email', 'profile'],
            'authorize_url' => 'https://provider.com/oauth/authorize',
            'access_token_url' => 'https://provider.com/oauth/token',
            'user_info_url' => 'https://provider.com/api/user',
        ],
    ],
    
  3. First Use Case: Authentication Flow Add a route to initiate OAuth:

    Route::get('/login/{provider}', [OAuthController::class, 'redirectToProvider']);
    

    Handle the callback:

    Route::get('/login/{provider}/callback', [OAuthController::class, 'handleProviderCallback']);
    

    Create a controller to manage the flow:

    use AWUniversity\OAuth2Client\Facades\OAuth2Client;
    
    public function redirectToProvider($provider)
    {
        return OAuth2Client::authorize($provider);
    }
    
    public function handleProviderCallback($provider)
    {
        $user = OAuth2Client::getUser($provider);
        // Store user data in session/database and redirect.
    }
    

Implementation Patterns

Common Workflows

  1. User Authentication

    • Use OAuth2Client::authorize($provider) to redirect users to the OAuth provider.
    • After callback, fetch user data with OAuth2Client::getUser($provider).
    • Map provider data to your user model (e.g., User::updateOrCreate()).
  2. Token Management

    • Refresh tokens silently (if supported):
      $token = OAuth2Client::refreshToken($provider, $refreshToken);
      
    • Store tokens in the database or session for future API calls.
  3. API Integration

    • Attach tokens to HTTP requests:
      $response = OAuth2Client::get($provider, 'https://api.provider.com/data', [
          'headers' => ['Authorization' => 'Bearer ' . $token],
      ]);
      
  4. Multi-Provider Support

    • Define multiple providers in config/oauth2-client.php and switch dynamically:
      $provider = request()->input('provider');
      $user = OAuth2Client::getUser($provider);
      

Integration Tips

  • Middleware: Protect routes with OAuth-verified users:

    Route::middleware(['auth.oauth'])->group(function () {
        // Protected routes
    });
    

    Define middleware in app/Http/Kernel.php:

    'auth.oauth' => \AWUniversity\OAuth2Client\Http\Middleware\AuthenticateOAuth::class,
    
  • Events: Listen for OAuth events (e.g., OAuthUserFetched) to log or process user data:

    Event::listen(OAuthUserFetched::class, function ($event) {
        // Custom logic (e.g., sync with CRM)
    });
    
  • Testing: Mock the OAuth provider in tests:

    $this->mock(OAuth2Client::class)
         ->shouldReceive('getUser')
         ->andReturn(['id' => 123, 'email' => 'user@example.com']);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2019; may lack support for modern OAuth2 features (e.g., PKCE, token introspection).
    • Mitigation: Fork the package or use alternatives like php-oauth2 if critical features are missing.
  2. Session Handling

    • The package relies on Laravel’s session. Ensure SESSION_DRIVER is configured (e.g., file, database).
    • Debugging: Clear sessions if tokens/redirects fail:
      php artisan session:clear
      
  3. Provider-Specific Quirks

    • Some providers (e.g., Google, GitHub) require additional scopes or custom parameters.
    • Tip: Check the provider’s docs and extend the config:
      'providers' => [
          'github' => [
              'scope' => ['user:email', 'read:org'], // Custom scopes
          ],
      ],
      
  4. CSRF Protection

    • Ensure APP_DEBUG=false in production to avoid CSRF token issues during redirects.

Debugging

  • Enable Logging: Add to config/oauth2-client.php:
    'debug' => env('APP_DEBUG', false),
    
  • Check Redirect URIs: Mismatched URIs (e.g., http vs https) cause callback failures.
  • Token Validation: Use OAuth2Client::validateToken($provider, $token) to debug token issues.

Extension Points

  1. Custom User Mapping Override the default user mapping logic by binding a service provider:

    OAuth2Client::extend('custom', function ($app) {
        return new CustomOAuthProvider($app['config']['oauth2-client.providers.custom']);
    });
    
  2. Add Provider-Specific Logic Extend the base OAuth2Client class or use facades to inject custom logic:

    OAuth2Client::afterUserFetch(function ($user, $provider) {
        if ($provider === 'google') {
            $user['provider_metadata'] = $this->parseGoogleData($user);
        }
    });
    
  3. API Client Customization Replace the underlying HTTP client (e.g., Guzzle) by binding a new instance:

    $client = new \GuzzleHttp\Client(['timeout' => 30]);
    OAuth2Client::setHttpClient($client);
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony