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 provides a fluent OAuth authentication interface for Laravel, with built-in drivers for Bitbucket, Facebook, GitHub, GitLab, Google, LinkedIn, Slack, Twitch, and X. Handles the boilerplate for social login and user retrieval.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel/socialite

For third-party providers (e.g., GitLab, Slack), install via Socialite Providers:

composer require socialiteproviders/manager
composer require socialiteproviders/<provider-name>
  1. Configuration: Publish the config file:

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

    Update .env with provider credentials (e.g., GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET).

  2. First Use Case: Redirect users to a provider (e.g., Google) and handle the callback:

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

    Key methods:

    • redirect(): Initiate OAuth flow.
    • user(): Fetch user data after callback.
    • stateless(): For stateless providers (e.g., Google ID tokens).

Implementation Patterns

Core Workflows

  1. Authentication Flow:

    // Route: GET /auth/google
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
    
    // Route: GET /auth/google/callback
    public function handleGoogleCallback()
    {
        try {
            $user = Socialite::driver('google')->user();
            // Create/attach user to your app (e.g., via `$user->email`).
        } catch (\Exception $e) {
            return redirect('/login')->withError($e->getMessage());
        }
    }
    
  2. User Data Handling: Extract data from the User object:

    $user = Socialite::driver('github')->user();
    $email = $user->getEmail();
    $avatar = $user->getAvatar();
    $token = $user->token; // Access token (if needed).
    
  3. Scopes and Customization: Configure scopes in config/services.php:

    'google' => [
        'scopes' => ['profile', 'email', 'openid'], // Custom scopes.
    ],
    

    Override scopes programmatically:

    Socialite::driver('github')->scopes(['user:email', 'read:org']);
    
  4. Testing with Fakes: Use the built-in FakeProvider for unit tests:

    use Laravel\Socialite\Contracts\Factory;
    use Laravel\Socialite\Testing\FakeProvider;
    
    public function testSocialiteLogin()
    {
        $fakeProvider = FakeProvider::create(['name' => 'Test User']);
        $this->app->instance(Factory::class, $fakeProvider);
    
        $user = Socialite::driver('fake')->user();
        $this->assertEquals('Test User', $user->getName());
    }
    
  5. Stateless Providers (e.g., Google ID Tokens):

    $user = Socialite::driver('google')->stateless()->user();
    // No redirect needed; uses ID token for validation.
    

Integration Tips

  • Middleware: Protect routes with auth middleware after social login.
  • Session Handling: Ensure session drivers are configured (e.g., file, database, redis).
  • Provider-Specific Quirks:
    • GitHub: Use scopes(['read:user']) for minimal permissions.
    • Facebook: For Limited Login, use Socialite::driver('facebook')->limited().
    • Twitter/X: Use Socialite::driver('twitter')->scopes(['users.read', 'tweet.read']).
  • Token Refresh: Use refreshToken() for providers supporting it (e.g., Google):
    $token = Socialite::driver('google')->refreshToken($refreshToken);
    

Gotchas and Tips

Pitfalls

  1. State Parameter Mismatch:

    • Issue: CSRF errors during callback due to state mismatch.
    • Fix: Ensure state is compared using hash_equals() (built-in since v5.26.1). Avoid manual state handling unless necessary.
  2. Missing Scopes:

    • Issue: Provider returns incomplete user data (e.g., no email).
    • Fix: Explicitly define scopes in config/services.php or via scopes():
      'github' => [
          'scopes' => ['user:email'], // Required for email access.
      ],
      
  3. Provider-Specific Bugs:

    • Facebook: Limited Login may fail if email scope is missing. Use:
      Socialite::driver('facebook')->limited()->scopes(['email']);
      
    • Twitter/X: OAuth 1.0a is deprecated. Use OAuth 2.0:
      'twitter' => [
          'oauth_version' => '2.0',
      ],
      
    • Google: Stateless mode requires openid scope:
      Socialite::driver('google')->stateless()->scopes(['openid']);
      
  4. Token Expiry:

    • Issue: Access tokens expire, causing 401 Unauthorized.
    • Fix: Implement token refresh logic or use short-lived tokens with stateless providers.
  5. Configuration Errors:

    • Issue: InvalidConfigurationException if client_id or client_secret is missing.
    • Fix: Verify .env and config/services.php:
      GOOGLE_CLIENT_ID=your_id
      GOOGLE_CLIENT_SECRET=your_secret
      GOOGLE_REDIRECT_URI=http://your-app.test/auth/google/callback
      

Debugging Tips

  1. Enable Logging: Add to config/logging.php to debug OAuth requests:

    'channels' => [
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/socialite.log'),
            'level' => 'debug',
        ],
    ],
    

    Log the raw user response:

    $user = Socialite::driver('github')->user();
    \Log::debug('Socialite User Data:', $user->toArray());
    
  2. Inspect Redirect URIs:

    • Ensure REDIRECT_URI matches exactly (including http vs https).
    • Use Socialite::driver('google')->getRedirectUrl() to debug the generated URL.
  3. Provider-Specific Tools:

Extension Points

  1. Custom User Mappers: Extend Laravel\Socialite\Contracts\User to map provider data to your user model:

    use Laravel\Socialite\Contracts\User as SocialiteUser;
    
    class CustomUser implements SocialiteUser {
        protected $user;
    
        public function __construct($user) {
            $this->user = $user;
        }
    
        public function getId() {
            return $this->user['id'] ?? null;
        }
    
        public function getEmail() {
            return $this->user['email'] ?? null;
        }
    
        // Implement other required methods...
    }
    

    Register the mapper in your SocialiteServiceProvider:

    public function boot()
    {
        Socialite::extend('custom', function ($app) {
            return new CustomProvider($app['http.client']);
        });
    }
    
  2. Custom Providers: Use SocialiteProviders/Manager to add unsupported providers:

    // config/socialite.php
    'providers' => [
        'custom' => [
            'client_id' => env('CUSTOM_CLIENT_ID'),
            'client_secret' => env('CUSTOM_CLIENT_SECRET'),
            'redirect' => env('CUSTOM_REDIRECT_URI'),
        ],
    ],
    

    Create a provider class extending SocialiteProviders\Manager\OAuth2\AbstractProvider.

  3. Decorators: Decorate the User object to add custom methods:

    Socialite::with(['user' => function ($user) {
        $user->setCustomAttribute('premium', true);
        return $user;
    }]);
    
  4. Testing:

    • Use FakeProvider for isolated tests (as shown above).
    • Mock HTTP clients for testing token responses:
      $this->mock(Http::class, function ($mock) {
          $mock->shouldReceive('post')
               ->withArgs(['https://api.github.com/login/oauth/access_token', ...])
               ->andReturn(['access_token' => 'fake_token']);
      });
      

Performance

  • Stateless Providers: Prefer for APIs (e.g., Google ID tokens) to avoid session storage.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony