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

Social Login Laravel Package

cresjie/social-login

Laravel 4 package for OAuth2 social authentication with Google, Facebook, Yahoo, and GitHub. Provides routes for redirect/login and callback authentication, returns user data, and supports config-based result filtering to normalize fields across providers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cresjie/social-login
    

    Publish the config file:

    php artisan vendor:publish --provider="Cresjie\SocialLogin\SocialLoginServiceProvider"
    
  2. Configuration: Edit config/social-login.php with your OAuth credentials (e.g., Google/Facebook API keys, secrets, and redirect URIs).

  3. First Use Case: Add a route for social login (e.g., Google):

    Route::get('/auth/google', 'Auth\SocialLoginController@redirectToProvider');
    Route::get('/auth/google/callback', 'Auth\SocialLoginController@handleProviderCallback');
    
  4. Controller Setup: Use the provided controller or extend it:

    use Cresjie\SocialLogin\Facades\SocialLogin;
    
    public function redirectToProvider($provider)
    {
        return SocialLogin::driver($provider)->redirect();
    }
    
    public function handleProviderCallback($provider)
    {
        $user = SocialLogin::driver($provider)->getUser();
        // Handle user creation/login logic here
    }
    

Implementation Patterns

Common Workflows

  1. User Authentication Flow:

    • Redirect to provider:
      return SocialLogin::driver('google')->redirect();
      
    • Handle callback:
      $user = SocialLogin::driver('google')->getUser();
      
    • Create/update user in your database:
      $existingUser = User::where('email', $user->email)->first();
      if (!$existingUser) {
          $existingUser = User::create([
              'name' => $user->name,
              'email' => $user->email,
              'provider_id' => $user->id,
              'provider' => 'google',
          ]);
      }
      Auth::login($existingUser);
      
  2. Custom User Mapping: Override the default user mapping by extending the SocialLogin facade or using a custom callback:

    SocialLogin::extend('github', function($app) {
        $app->useCustomUserMapping(function ($providerUser) {
            return [
                'name' => $providerUser->name,
                'email' => $providerUser->email,
                'avatar' => $providerUser->avatar_url,
            ];
        });
    });
    
  3. Session Handling: Use Laravel's built-in session to persist user data after login:

    session(['social_login_data' => $user->toArray()]);
    
  4. Multi-Provider Support: Dynamically handle multiple providers in a single route:

    public function handleSocialLogin($provider)
    {
        try {
            $user = SocialLogin::driver($provider)->getUser();
            // Logic for user creation/login
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last release in 2015 means it may not support modern Laravel versions (e.g., 8/9/10) or PHP 8.x out of the box.
    • Fix: Use a compatibility layer or fork the package. Check for issues with:
      • use Illuminate\Auth\AuthManager (deprecated in Laravel 8+).
      • Session or Redirect facade usage (updated in newer Laravel versions).
  2. OAuth 2.0 Changes:

    • Some providers (e.g., Facebook, Google) have updated their OAuth scopes or endpoints since 2015.
    • Tip: Verify the config/social-login.php endpoints against the latest provider documentation. Example for Google:
      'google' => [
          'client_id' => env('GOOGLE_CLIENT_ID'),
          'client_secret' => env('GOOGLE_CLIENT_SECRET'),
          'redirect' => env('GOOGLE_REDIRECT_URI'),
          'scope' => ['email', 'profile'], // Update scopes as needed
      ],
      
  3. State Parameter:

    • The package may not include CSRF protection for the OAuth state parameter by default.
    • Fix: Manually generate and validate a state token:
      $state = Str::random(40);
      session(['oauth_state' => $state]);
      return SocialLogin::driver('google')->setState($state)->redirect();
      
      In the callback:
      if (session('oauth_state') !== $providerUser->getState()) {
          throw new \Exception('State mismatch');
      }
      
  4. User Data Format:

    • The getUser() method may return raw provider data in an unexpected format.
    • Tip: Inspect $user->toArray() or dump the object to understand the structure:
      dd(SocialLogin::driver('github')->getUser());
      

Debugging Tips

  1. Enable Debugging: Add this to config/social-login.php to log provider responses:

    'debug' => env('APP_DEBUG', false),
    
  2. Provider-Specific Errors:

    • Check the provider's developer console (e.g., Google Cloud Console) for OAuth errors.
    • Common issues:
      • Redirect URI mismatch: Ensure redirect in config matches your app's URL.
      • Invalid credentials: Regenerate API keys in the provider dashboard.
  3. Testing Locally: Use tools like ngrok to expose your local dev server for OAuth callbacks:

    ngrok http 8000
    

    Update the redirect URI in config/social-login.php to include your ngrok URL (e.g., https://abc123.ngrok.io/auth/google/callback).

Extension Points

  1. Custom Providers: Add support for unsupported providers (e.g., Twitter, LinkedIn) by extending the SocialLogin facade:

    SocialLogin::extend('twitter', function($app) {
        $app->useProvider(\Cresjie\SocialLogin\Providers\TwitterProvider::class);
    });
    
  2. Post-Login Redirects: Override the default redirect logic in your callback:

    return redirect()->intended('dashboard'); // Use Laravel's intended redirect
    
  3. User Sync Logic: Create a service to handle user creation/login consistently:

    class SocialAuthService {
        public function handleLogin($providerUser, $providerName) {
            $user = User::firstOrCreate([
                'provider_id' => $providerUser->id,
                'provider' => $providerName,
            ], [
                'name' => $providerUser->name,
                'email' => $providerUser->email,
            ]);
            Auth::login($user);
            return $user;
        }
    }
    
  4. Rate Limiting: Add rate limiting to prevent abuse of social login endpoints:

    Route::middleware(['throttle:10,1'])->group(function () {
        Route::get('/auth/google', 'Auth\SocialLoginController@redirectToProvider');
    });
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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