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

overtrue/socialite

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require overtrue/socialite
    

    Ensure PHP ≥ 8.0.2.

  2. Basic Configuration: Define provider configs in an array (e.g., config/social.php):

    return [
        'github' => [
            'client_id'     => env('GITHUB_CLIENT_ID'),
            'client_secret' => env('GITHUB_CLIENT_SECRET'),
            'redirect_uri'  => env('GITHUB_REDIRECT_URI'),
        ],
    ];
    
  3. First Use Case: Redirect users to GitHub for OAuth:

    use Overtrue\Socialite\SocialiteManager;
    
    $config = require __DIR__.'/config/social.php';
    $socialite = new SocialiteManager($config);
    
    $url = $socialite->create('github')->redirect();
    return redirect($url);
    
  4. Callback Handling: Process the OAuth code in a callback route:

    $code = request()->query('code');
    $user = $socialite->create('github')->userFromCode($code);
    // Access user data: $user->getEmail(), $user->getName(), etc.
    

Implementation Patterns

Core Workflows

  1. Provider Initialization:

    $socialite = new SocialiteManager($config);
    $github = $socialite->create('github'); // or custom alias
    
  2. Redirect Flow:

    $authUrl = $github->redirect(); // Returns URL for OAuth redirect
    
  3. User Data Fetching:

    $user = $github->userFromCode($code); // After callback
    $user->getId();       // Unique provider ID
    $user->getEmail();    // Email (if available)
    $user->getAvatar();   // Profile image URL
    
  4. Token Management:

    $token = $github->getAccessToken(); // After userFromCode()
    $user = $github->userFromToken($token); // Re-fetch user
    

Integration Tips

  • Laravel Integration: Use overtrue/laravel-socialite for seamless Laravel integration (e.g., middleware, service providers). Example:

    use Overtrue\LaravelSocialite\Facades\Socialite;
    
    $user = Socialite::driver('github')->user();
    
  • Custom Scopes:

    $url = $github->scopes(['user:email'])->redirect();
    
  • State Parameter:

    $url = $github->state('custom_state')->redirect();
    // Verify in callback: $github->getState() === 'custom_state'
    
  • Session Storage: Store tokens/user data in the session for later use:

    session(['github_token' => $token]);
    
  • Multi-Provider Support:

    $providers = ['github', 'google'];
    foreach ($providers as $provider) {
        $socialite->create($provider)->redirect();
    }
    

Gotchas and Tips

Common Pitfalls

  1. Redirect URI Mismatch:

    • Ensure redirect_uri in config matches the callback URL registered in the provider’s developer console.
    • Use absolute URLs (e.g., https://example.com/callback).
  2. State Validation:

    • Always validate the state parameter in callbacks to prevent CSRF:
      if ($github->getState() !== session('oauth_state')) {
          throw new \Exception('State mismatch!');
      }
      
  3. Token Expiry:

    • Tokens expire. Handle Overtrue\Socialite\Exceptions\TokenExpiredException by refreshing tokens or re-authenticating.
  4. Provider-Specific Quirks:

    • Weibo: Requires scope parameter (e.g., all).
    • Alipay: Uses RSA2 private keys (store securely, avoid hardcoding).
    • Douyin/Toutiao/Xigua: Require openid for token-based user fetching:
      $user = $douyin->withOpenId($openid)->userFromToken($token);
      
  5. CORS Issues:

    • If using popup mode (e.g., Baidu), ensure the callback URL is whitelisted in the provider’s settings.

Debugging Tips

  1. Enable Debug Mode:

    $socialite->setDebug(true); // Logs OAuth requests/responses
    
  2. Inspect Raw Responses:

    $response = $github->getAccessTokenResponse($code);
    // Dump $response for debugging
    
  3. Handle Provider Errors: Catch exceptions for specific providers:

    try {
        $user = $github->userFromCode($code);
    } catch (\Overtrue\Socialite\Exceptions\InvalidStateException $e) {
        // Handle invalid state
    }
    

Extension Points

  1. Custom User Model: Map provider data to your user model:

    $userData = $github->user()->toArray();
    $yourUser = YourUser::updateOrCreate(
        ['provider_id' => $userData['id']],
        [
            'name' => $userData['name'],
            'email' => $userData['email'] ?? null,
        ]
    );
    
  2. Extend Providers: Add support for unsupported providers by implementing ProviderInterface:

    class CustomProvider implements \Overtrue\Socialite\Contracts\ProviderInterface {
        public function getAuthUrl($state) { /* ... */ }
        public function getAccessToken($code) { /* ... */ }
        public function getUserByToken($token) { /* ... */ }
    }
    

    Register it:

    $socialite->extend('custom', function ($config) {
        return new CustomProvider($config);
    });
    
  3. Override Default Scopes:

    $github->scopes(['user', 'repo']); // Override default scopes
    
  4. Custom Redirect Logic:

    $github->setRedirectUrlGenerator(function ($url) {
        return str_replace('https://', 'http://', $url); // Force HTTP
    });
    

Configuration Quirks

  • Legacy Key Support: The package supports old keys like redirect or redirect_url for backward compatibility.
  • Environment Variables: Use Laravel’s .env or PHP’s getenv() for sensitive data (e.g., client_secret).
  • Provider Aliases: Use aliases for clarity (e.g., 'twitter' => ['provider' => 'twitter', ...]).
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