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 Steps

  1. Installation:

    composer require overtrue/socialite
    

    For Laravel, use overtrue/laravel-socialite for seamless integration.

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

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

    use Overtrue\Socialite\SocialiteManager;
    
    $socialite = new SocialiteManager(config('socialite'));
    $url = $socialite->create('github')->redirect();
    return redirect($url);
    
  4. Handle Callback: After user authorization, exchange the code for user data:

    $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:

    • Use SocialiteManager to manage multiple providers:
      $socialite = new SocialiteManager($config);
      $github = $socialite->create('github');
      
  2. Redirect Flow:

    • Initiate OAuth flow:
      $authUrl = $socialite->create('wechat')->redirect();
      return redirect($authUrl);
      
  3. Callback Handling:

    • Exchange code for user data:
      $user = $socialite->create('wechat')->userFromCode($code);
      
  4. User Data Extraction:

    • Access standardized user fields:
      $email = $user->getEmail();
      $name = $user->getName();
      $avatar = $user->getAvatar();
      

Integration Tips

  1. Laravel Integration:

    • Use middleware to validate state tokens:
      public function handle(Request $request, Closure $next) {
          if ($request->has('state') && !hash_equals(session('oauth_state'), $request->state)) {
              throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
          }
          return $next($request);
      }
      
  2. Custom User Mapping:

    • Map provider data to your user model:
      $userData = $user->getOriginal();
      $yourUser = YourUser::updateOrCreate(
          ['email' => $userData['email']],
          ['name' => $userData['name'], 'provider_id' => $user->getId()]
      );
      
  3. Session Persistence:

    • Store user data in session after login:
      session(['user' => $yourUser]);
      
  4. Multi-Provider Logins:

    • Dynamically switch providers:
      $provider = request()->input('provider'); // e.g., 'github', 'wechat'
      $socialite->create($provider)->redirect();
      
  5. Scoped Access:

    • Request specific permissions (e.g., for Baidu):
      $socialite->create('baidu')->scopes(['basic'])->redirect();
      

Gotchas and Tips

Pitfalls

  1. Redirect URI Mismatch:

    • Ensure redirect_uri in config matches the callback URL registered in the provider’s dashboard.
    • Fix: Double-check the URI in both config and provider settings.
  2. State Token Validation:

    • Always validate the state parameter to prevent CSRF attacks.
    • Fix: Use Laravel’s built-in CSRF protection or manually validate:
      if (!hash_equals(session('oauth_state'), $request->state)) {
          abort(403);
      }
      
  3. Provider-Specific Quirks:

    • WeChat/Open Platform: Requires component config for third-party platforms.
      'wechat' => [
          'client_id' => '...',
          'component' => [
              'app_id' => env('WECHAT_COMPONENT_APP_ID'),
              'token' => env('WECHAT_COMPONENT_TOKEN'),
          ],
      ]
      
    • Alipay: Only supports RSA2 private key authentication.
    • Douyin/Toutiao/Xigua: Require openid for userFromToken():
      $user = $socialite->create('douyin')->withOpenId($openId)->userFromToken($token);
      
  4. Token Expiry:

    • Some providers (e.g., WeChat) return short-lived tokens. Cache tokens and refresh them proactively:
      $token = $socialite->create('wechat')->getAccessToken();
      Cache::put('wechat_token', $token, now()->addHours(1));
      
  5. Error Handling:

    • Wrap provider calls in try-catch blocks:
      try {
          $user = $socialite->create('github')->userFromCode($code);
      } catch (\Overtrue\Socialite\Exceptions\InvalidStateException $e) {
          Log::error($e->getMessage());
          abort(403);
      }
      

Debugging Tips

  1. Enable Debug Mode:

    • Set debug: true in config to log OAuth requests/responses:
      $socialite = new SocialiteManager($config, [
          'debug' => true,
      ]);
      
  2. Inspect Raw Responses:

    • Access raw provider responses for debugging:
      $response = $socialite->create('github')->getAccessTokenResponse($code);
      dd($response->getBody());
      
  3. Provider-Specific Logs:

    • Check provider dashboards (e.g., GitHub OAuth Apps) for failed requests.

Extension Points

  1. Custom Providers:

    • Extend support for unsupported platforms by implementing ProviderInterface:
      class CustomProvider implements \Overtrue\Socialite\Contracts\ProviderInterface {
          public function getAuthUrl($state) { ... }
          public function getAccessToken($code) { ... }
          public function getUserByToken($token) { ... }
      }
      
    • Register the provider:
      $socialite->extend('custom', function ($config) {
          return new CustomProvider($config);
      });
      
  2. Override User Model:

    • Extend the User class to add provider-specific fields:
      class SocialUser extends \Overtrue\Socialite\Providers\User {
          public function getProviderId() {
              return $this->original['provider_id'] ?? null;
          }
      }
      
    • Bind to the provider:
      $socialite->extend('github', function ($config) {
          $provider = new \Overtrue\Socialite\Providers\GitHubProvider($config);
          $provider->setUserClass(SocialUser::class);
          return $provider;
      });
      
  3. Dynamic Config Loading:

    • Load configs from environment variables or cache:
      $config = [
          'github' => [
              'client_id' => env('GITHUB_CLIENT_ID'),
              // ...
          ],
      ];
      
  4. Rate Limiting:

    • Implement middleware to throttle OAuth requests:
      public function handle($request, Closure $next) {
          if ($request->is('socialite/*')) {
              $key = $request->ip().'|'.$request->provider;
              if (Cache::has($key)) {
                  abort(429, 'Too many requests');
              }
              Cache::put($key, true, now()->addMinutes(1));
          }
          return $next($request);
      }
      
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