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

Manager Laravel Package

socialiteproviders/manager

Laravel SocialiteProviders Manager lets you add or override Socialite OAuth providers with deferred loading, easy Lumen support, configurable stateless mode, dynamic config overrides, and direct .env variable retrieval for simpler setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require socialiteproviders/manager
    
  2. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="SocialiteProviders\Manager\ManagerServiceProvider"
    
  3. Register the service provider in config/app.php (automatically added in Laravel 5.5+):
    'providers' => [
        // ...
        SocialiteProviders\Manager\ManagerServiceProvider::class,
    ],
    
  4. Add a provider (e.g., GitHub):
    composer require socialiteproviders/github
    
  5. Configure the provider in .env:
    GITHUB_CLIENT_ID=your_client_id
    GITHUB_CLIENT_SECRET=your_client_secret
    GITHUB_REDIRECT_URI=http://your-app.com/auth/github/callback
    

First Use Case: Redirect to GitHub OAuth

use Laravel\Socialite\Facades\Socialite;

return Socialite::driver('github')->redirect();
  • The package automatically loads the GitHub provider when Socialite::driver('github') is called.
  • No manual instantiation or service binding required.

Implementation Patterns

1. Adding a New Provider

Step 1: Install the Provider Package

composer require socialiteproviders/{provider-name}

Example: socialiteproviders/discord.

Step 2: Configure .env

DISCORD_CLIENT_ID=your_id
DISCORD_CLIENT_SECRET=your_secret
DISCORD_REDIRECT_URI=http://your-app.com/auth/discord/callback

Step 3: Use the Provider

// Redirect to Discord OAuth
return Socialite::driver('discord')->redirect();

// Handle callback
$user = Socialite::driver('discord')->user();

2. Overriding a Built-in Provider

To override a default provider (e.g., Facebook), create a custom provider with the same name (e.g., facebook). Example: Custom Facebook provider with extended scopes.

// app/Providers/SocialiteServiceProvider.php
use SocialiteProviders\Manager\SocialiteWasCalled;

public function boot()
{
    Socialite::extend('facebook', function ($app) {
        $config = $app->make('config')->get('services.facebook');
        $config['scopes'] = ['email', 'public_profile', 'user_friends']; // Extended scopes
        return Socialite::buildProvider(\SocialiteProviders\Facebook\FacebookExtender::class, $config);
    });
}

3. Dynamic Provider Configuration

Pass runtime configurations (e.g., per-tenant credentials or conditional stateless mode):

$clientId = 'tenant_specific_id';
$clientSecret = 'tenant_specific_secret';
$redirectUri = 'https://tenant.example.com/auth/callback';
$config = new \SocialiteProviders\Manager\Config($clientId, $clientSecret, $redirectUri);

return Socialite::driver('github')
    ->setConfig($config)
    ->stateless() // Optional: Disable session storage
    ->redirect();

4. Accessing Raw OAuth Response

Extend the provider to include the full response body (e.g., refresh_token):

// In your custom provider class (extends \SocialiteProviders\Manager\OAuth2\AbstractProvider)
protected function getAccessTokenResponse($code)
{
    $response = parent::getAccessTokenResponse($code);
    $this->user['accessTokenResponseBody'] = json_decode($response->getBody(), true);
    return $response;
}

// Usage:
$user = Socialite::driver('github')->user();
$refreshToken = $user->accessTokenResponseBody['refresh_token'] ?? null;

5. Lumen Integration

The package supports stateless mode by default in Lumen:

// config/services.php
'socialite' => [
    'stateless' => true, // Disable session storage
],
  • Providers are lazy-loaded on demand, reducing memory usage in high-traffic APIs.

6. Event-Driven Extensions

Extend Socialite dynamically via events (e.g., add a provider only for specific routes):

// app/Providers/EventServiceProvider.php
protected $listen = [
    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        \App\Listeners\ExtendSocialiteForAdmin::class,
    ],
];

// Listener: Add a provider only for admin routes
public function handle(SocialiteWasCalled $event)
{
    if (request()->is('admin/*')) {
        $event->extendSocialite('custom-admin-provider', \App\Providers\CustomAdminProvider::class);
    }
}

7. Multi-Tenant Provider Routing

Route providers based on tenant context (e.g., tenant1 uses GitHub, tenant2 uses GitLab):

// Middleware or service
public function getProvider()
{
    $tenant = auth()->user()->tenant;
    return $tenant->provider === 'github' ? 'github' : 'gitlab';
}

// Usage
return Socialite::driver($this->getProvider())->redirect();

Gotchas and Tips

Pitfalls

  1. Provider Not Found Errors

    • Cause: Forgetting to install the provider package (e.g., socialiteproviders/github).
    • Fix: Run composer require socialiteproviders/{provider} and ensure .env is configured.
    • Debug: Check config/socialite.php for loaded providers.
  2. Stateless Mode Conflicts

    • Cause: Using stateless() after calling redirect() or user().
    • Fix: Set stateless mode before any Socialite method calls:
      Socialite::driver('github')->stateless()->redirect();
      
  3. Event Listener Not Triggering

    • Cause: Not registering the listener in EventServiceProvider.
    • Fix: Add the listener to the $listen array and ensure the event class (SocialiteWasCalled) is imported.
  4. Dynamic Config Overrides

    • Cause: setConfig() must be called before redirect() or user().
    • Fix: Chain methods in the correct order:
      Socialite::driver('github')
          ->setConfig($config)
          ->redirect(); // Works
      // vs.
      Socialite::driver('github')->redirect()->setConfig($config); // Fails
      
  5. Laravel 10+ Caching Issues

    • Cause: Provider classes may be cached aggressively in Laravel 10+.
    • Fix: Clear the config cache:
      php artisan config:clear
      

Debugging Tips

  1. Log Provider Instantiation Override SocialiteWasCalled to log when providers are loaded:

    public function handle(SocialiteWasCalled $event)
    {
        \Log::info('Provider loaded:', ['provider' => $event->providerName]);
    }
    
  2. Inspect Raw Responses Dump the full OAuth response for debugging:

    $user = Socialite::driver('github')->user();
    \Log::debug('Raw user data:', $user->toArray());
    
  3. Validate .env Config Use Laravel’s config helper to verify loaded providers:

    $providers = config('services.socialite.providers', []);
    \Log::debug('Loaded providers:', $providers);
    

Extension Points

  1. Custom Provider Abstraction Extend \SocialiteProviders\Manager\OAuth2\AbstractProvider to add:

    • Custom scopes.
    • Additional user fields (e.g., extra['custom_field']).
    • Conditional logic (e.g., tenant-specific mappings).
  2. Provider Factory Create a dynamic provider factory for multi-tenant apps:

    public function getProviderClass(string $name): string
    {
        return match ($name) {
            'github' => \SocialiteProviders\GitHub\GitHubExtender::class,
            'gitlab' => \SocialiteProviders\GitLab\GitLabExtender::class,
            default => parent::getProviderClass($name),
        };
    }
    
  3. Stateless Mode Optimization For Lumen APIs, disable session storage entirely:

    // config/socialite.php
    'stateless' => env('APP_ENV') !== 'local',
    
  4. Provider Whitelisting Restrict available providers for security:

    // app/Providers/SocialiteServiceProvider.php
    public function boot()
    {
        Socialite::extend('github', function ($app) {
            if (!in_array('github', config('socialite.allowed_providers'))) {
                abort(403);
            }
            // ...
        });
    }
    

Performance Tips

  1. Lazy-Load Providers The package **defer-loads
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope