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

Socialite Laravel Package

laravel/socialite

Laravel Socialite offers a fluent interface for OAuth authentication in Laravel with providers like GitHub, Google, Facebook, GitLab, LinkedIn, Slack, Twitch, X, and more. It removes most of the boilerplate needed for social login.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/socialite
    
  2. Publish Config:

    php artisan vendor:publish --provider="Laravel\Socialite\SocialiteServiceProvider"
    

    This generates config/services.php with provider credentials (client ID, secret, etc.).

  3. Register Provider: Add your provider (e.g., Google) to config/services.php:

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
    
  4. First Use Case: Redirect users to a provider and handle the callback in a controller:

    use Laravel\Socialite\Facades\Socialite;
    
    // Redirect to Google auth
    return Socialite::driver('google')->redirect();
    
    // Handle callback
    $user = Socialite::driver('google')->user();
    

Key Files to Review

  • config/services.php: Provider configurations.
  • app/Providers/AuthServiceProvider.php: Register callbacks (if using routes).
  • routes/web.php: Define auth routes (e.g., /auth/google/callback).

Implementation Patterns

Core Workflow

  1. Redirect Users:

    return Socialite::driver('github')->redirect();
    
    • Generates a URL with a state parameter for CSRF protection.
  2. Handle Callback:

    $user = Socialite::driver('github')->user();
    
    • Returns a Laravel\Socialite\Contracts\User object with raw data (e.g., id, email, name, avatar).
  3. Map to Local User:

    $existingUser = User::where('email', $user->email)->first();
    if (!$existingUser) {
        $existingUser = User::create([
            'name' => $user->name,
            'email' => $user->email,
            'provider_id' => $user->id,
        ]);
    }
    auth()->login($existingUser);
    

Common Patterns

  • Scopes: Request additional permissions (e.g., email for GitHub):

    $user = Socialite::driver('github')->scopes(['email'])->user();
    

    Configure scopes in config/services.php:

    'github' => [
        'scopes' => ['user:email'],
    ],
    
  • Custom User Fields: Access raw data or map custom fields:

    $user->getAvatar(); // Avatar URL
    $user->getOriginal(); // Raw OAuth response
    
  • Testing: Use Socialite::fake() for unit tests:

    Socialite::fake()->shouldReceive('user')->andReturn($fakeUser);
    
  • State Management: Customize the state parameter for tracking:

    Socialite::with(['state' => 'custom_state']);
    

Integration Tips

  • Middleware: Protect callback routes with auth or custom middleware.

    Route::get('/auth/{provider}/callback', [AuthController::class, 'handleProviderCallback']);
    
  • Session Handling: Ensure sessions are enabled (SESSION_DRIVER=file or database in .env).

  • Provider-Specific Quirks:

    • Google: Use stateless ID tokens for SPAs:
      $user = Socialite::driver('google')->stateless()->user();
      
    • Twitter/X: Configure OAuth version (1 or 2) in config/services.php.

Gotchas and Tips

Pitfalls

  1. Missing Config:

    • Error: InvalidConfigurationException if client_id/client_secret are missing.
    • Fix: Verify config/services.php and .env variables.
  2. CSRF State Mismatch:

    • Error: InvalidStateException if the state parameter doesn’t match.
    • Fix: Ensure APP_URL and redirect URIs match exactly (case-sensitive).
  3. Scopes Not Requested:

    • Error: Missing email or other fields in the user object.
    • Fix: Explicitly add scopes:
      Socialite::driver('github')->scopes(['user:email']);
      
  4. Provider-Specific Issues:

    • GitHub: Limited login may return incomplete data (e.g., no email). Fix: Use scopes(['user:email']) or handle null emails.
    • Facebook: Limited login requires openid scope:
      Socialite::driver('facebook')->scopes(['email', 'openid']);
      
  5. Laravel Octane:

    • Issue: Config updates may not reflect due to caching.
    • Fix: Use Socialite::reset() or restart Octane.

Debugging Tips

  • Log Raw Data:

    dd($user->getOriginal());
    

    Inspect the raw OAuth response for missing fields.

  • Enable Debugging: Set debug: true in config/services.php for verbose logs.

  • State Parameter: Manually verify the state parameter in the callback URL matches the session.

Extension Points

  1. Custom Providers: Extend Laravel\Socialite\Two\AbstractProvider for unsupported providers. Example:

    namespace App\Providers;
    
    use Laravel\Socialite\Two\ProviderInterface;
    
    class CustomProvider extends \Laravel\Socialite\Two\AbstractProvider implements ProviderInterface {
        // Implement required methods
    }
    
  2. Override User Model: Replace the default User model in config/services.php:

    'models' => [
        'user' => \App\Models\CustomUser::class,
    ],
    
  3. Testing Fakes: Mock providers for tests:

    Socialite::fake()->shouldReceive('user')->once()->andReturn($fakeUser);
    
  4. Custom Scopes: Dynamically set scopes in runtime:

    $scopes = ['custom_scope1', 'custom_scope2'];
    $user = Socialite::driver('github')->scopes($scopes)->user();
    

Configuration Quirks

  • Redirect URI: Must match exactly (including http vs https) in both .env and provider dashboard. Example:

    GOOGLE_REDIRECT_URI=https://your-app.test/auth/google/callback
    
  • PKCE for SPAs: Enable for single-page apps to prevent code flow attacks:

    Socialite::driver('google')->enablePKCE();
    
  • Stateless Tokens: Use for APIs without sessions:

    $user = Socialite::driver('google')->stateless()->user();
    

Performance

  • Avoid Redundant Calls: Cache the Socialite instance if used repeatedly in a request:

    $socialite = Socialite::driver('github');
    $user = $socialite->user();
    
  • Refresh Tokens: Use refreshToken() for long-lived access:

    $token = $user->token;
    $refreshedToken = Socialite::driver('google')->refreshToken($token);
    
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.
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
anil/file-picker
broqit/fields-ai