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 adds a clean, fluent OAuth authentication layer for Laravel. Supports Bitbucket, Facebook, GitHub, GitLab, Google, LinkedIn, Slack, Twitch, and X, handling the boilerplate for social login and user retrieval.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/socialite
    

    Publish the config file:

    php artisan vendor:publish --provider="Laravel\Socialite\SocialiteServiceProvider"
    
  2. Configure Providers: Edit config/services.php with your OAuth credentials (e.g., for Google):

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
    
  3. First Use Case: Add a route to redirect to Google OAuth:

    use Laravel\Socialite\Facades\Socialite;
    
    Route::get('/login/google', function () {
        return Socialite::driver('google')->redirect();
    });
    

    Handle the callback:

    Route::get('/login/google/callback', function () {
        $user = Socialite::driver('google')->user();
        // Use $user data (e.g., email, name, avatar)
        return redirect('/dashboard');
    });
    

Where to Look First

  • Documentation: Laravel Socialite Docs
  • Providers: Check config/services.php for available drivers (Google, GitHub, Facebook, etc.).
  • Testing: Use Socialite::fake() for unit tests (added in v5.24.0).

Implementation Patterns

Core Workflow

  1. Redirect to Provider:

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

    $user = Socialite::driver('github')->user();
    
    • Returns a Laravel\Socialite\Contracts\User object with raw data from the provider.
  3. Map User Data:

    $authUser = User::updateOrCreate(
        ['email' => $user->email],
        [
            'name' => $user->name,
            'avatar' => $user->avatar_original,
        ]
    );
    

Common Patterns

  • Scopes: Configure scopes in config/services.php or dynamically:

    Socialite::driver('github')->scopes(['repo', 'user:email'])->redirect();
    
  • Custom User Fields: Extend the User model or use a mapper:

    $userData = $user->getOriginal();
    // Custom logic to map fields.
    
  • State Management: Manually validate state tokens if needed:

    $state = request()->query('state');
    if (!hash_equals(session('oauth_state'), $state)) {
        abort(403);
    }
    
  • Token Refresh: Use the refreshToken() method (v5.11.0+):

    $token = Socialite::driver('google')->refreshToken($refreshToken);
    

Integration Tips

  • Middleware: Protect routes with auth:socialite or custom middleware.
  • Events: Dispatch events (e.g., SocialiteWasCalled) for logging/auditing.
  • Testing: Use fakes for isolated tests:
    Socialite::fake()->shouldReceive('user')->andReturn($fakeUser);
    

Gotchas and Tips

Pitfalls

  1. State Token Mismatch:

    • Always validate the state parameter in callbacks to prevent CSRF attacks.
    • Use hash_equals() for constant-time comparison (v5.26.1+).
  2. Provider-Specific Quirks:

    • Google: Limited login may return null for email if not requested.
    • Twitter/X: OAuth 1.0a vs. OAuth 2.0 requires config adjustments.
    • Facebook: Avatar URLs may need manual validation (v5.23.0+).
  3. Configuration Errors:

    • Missing or invalid redirect URI in config/services.php will cause silent failures.
    • Use Socialite::driver()->getConfig() to debug config issues.
  4. PKCE (OAuth 2.0):

    • Enabled by default for most providers. Disable with:
      Socialite::driver('github')->enablePKCE(false);
      

Debugging Tips

  • Log Raw Data:
    \Log::info('Socialite User Data:', $user->getOriginal());
    
  • Check Headers: Some providers (e.g., Slack) require custom headers. Override with:
    Socialite::driver('slack')->withHeaders(['Authorization' => 'Bearer token']);
    

Extension Points

  1. Custom Providers: Use Socialite Providers for unsupported platforms. Example structure:

    app/Providers/
      MyCustomProvider.php (extends Laravel\Socialite\Providers\OAuth2\AbstractProvider)
    
  2. User Mappers: Create a mapper class to transform provider data:

    class GitHubUserMapper implements UserMapperInterface {
        public function map(User $user): array {
            return [
                'email' => $user->getEmail(),
                'name'  => $user->getName(),
            ];
        }
    }
    

    Register it in AuthServiceProvider:

    Socialite::extend('github', function ($app) {
        return new GitHubProvider($app, new GitHubUserMapper());
    });
    
  3. Testing Fakes: Mock responses for unit tests:

    Socialite::fake([
        'provider' => 'github',
        'user' => ['id' => 123, 'name' => 'Test User'],
    ]);
    

Configuration Quirks

  • Scopes: Some providers (e.g., GitHub) allow dynamic scope merging. Use:
    Socialite::driver('github')->scopes(['repo'])->stateless();
    
  • Stateless Tokens: Google (v5.22.0+) supports stateless ID tokens:
    $user = Socialite::driver('google')->stateless()->user();
    
  • Environment Variables: Ensure .env variables are loaded (e.g., GOOGLE_CLIENT_ID). Use:
    php artisan config:clear
    
    if changes aren’t reflected.

Performance

  • Caching: Cache user data if the provider supports it (e.g., GitHub tokens).
  • Avoid Redundant Calls: Reuse the Socialite instance in a single request to avoid re-fetching config.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport