laravel/socialite
Laravel Socialite offers a fluent interface for OAuth authentication in Laravel with providers like GitHub, Google, Facebook, GitLab, LinkedIn, Slack, Twitch, X, and more. It removes most of the boilerplate needed for social login.
Installation:
composer require laravel/socialite
Publish Config:
php artisan vendor:publish --provider="Laravel\Socialite\SocialiteServiceProvider"
This generates config/services.php with provider credentials (client ID, secret, etc.).
Register Provider:
Add your provider (e.g., Google) to config/services.php:
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
First Use Case: Redirect users to a provider and handle the callback in a controller:
use Laravel\Socialite\Facades\Socialite;
// Redirect to Google auth
return Socialite::driver('google')->redirect();
// Handle callback
$user = Socialite::driver('google')->user();
config/services.php: Provider configurations.app/Providers/AuthServiceProvider.php: Register callbacks (if using routes).routes/web.php: Define auth routes (e.g., /auth/google/callback).Redirect Users:
return Socialite::driver('github')->redirect();
state parameter for CSRF protection.Handle Callback:
$user = Socialite::driver('github')->user();
Laravel\Socialite\Contracts\User object with raw data (e.g., id, email, name, avatar).Map to Local User:
$existingUser = User::where('email', $user->email)->first();
if (!$existingUser) {
$existingUser = User::create([
'name' => $user->name,
'email' => $user->email,
'provider_id' => $user->id,
]);
}
auth()->login($existingUser);
Scopes: Request additional permissions (e.g., email for GitHub):
$user = Socialite::driver('github')->scopes(['email'])->user();
Configure scopes in config/services.php:
'github' => [
'scopes' => ['user:email'],
],
Custom User Fields: Access raw data or map custom fields:
$user->getAvatar(); // Avatar URL
$user->getOriginal(); // Raw OAuth response
Testing:
Use Socialite::fake() for unit tests:
Socialite::fake()->shouldReceive('user')->andReturn($fakeUser);
State Management:
Customize the state parameter for tracking:
Socialite::with(['state' => 'custom_state']);
Middleware:
Protect callback routes with auth or custom middleware.
Route::get('/auth/{provider}/callback', [AuthController::class, 'handleProviderCallback']);
Session Handling:
Ensure sessions are enabled (SESSION_DRIVER=file or database in .env).
Provider-Specific Quirks:
stateless ID tokens for SPAs:
$user = Socialite::driver('google')->stateless()->user();
config/services.php.Missing Config:
InvalidConfigurationException if client_id/client_secret are missing.config/services.php and .env variables.CSRF State Mismatch:
InvalidStateException if the state parameter doesn’t match.APP_URL and redirect URIs match exactly (case-sensitive).Scopes Not Requested:
email or other fields in the user object.Socialite::driver('github')->scopes(['user:email']);
Provider-Specific Issues:
scopes(['user:email']) or handle null emails.openid scope:
Socialite::driver('facebook')->scopes(['email', 'openid']);
Laravel Octane:
Socialite::reset() or restart Octane.Log Raw Data:
dd($user->getOriginal());
Inspect the raw OAuth response for missing fields.
Enable Debugging:
Set debug: true in config/services.php for verbose logs.
State Parameter:
Manually verify the state parameter in the callback URL matches the session.
Custom Providers:
Extend Laravel\Socialite\Two\AbstractProvider for unsupported providers.
Example:
namespace App\Providers;
use Laravel\Socialite\Two\ProviderInterface;
class CustomProvider extends \Laravel\Socialite\Two\AbstractProvider implements ProviderInterface {
// Implement required methods
}
Override User Model:
Replace the default User model in config/services.php:
'models' => [
'user' => \App\Models\CustomUser::class,
],
Testing Fakes: Mock providers for tests:
Socialite::fake()->shouldReceive('user')->once()->andReturn($fakeUser);
Custom Scopes: Dynamically set scopes in runtime:
$scopes = ['custom_scope1', 'custom_scope2'];
$user = Socialite::driver('github')->scopes($scopes)->user();
Redirect URI:
Must match exactly (including http vs https) in both .env and provider dashboard.
Example:
GOOGLE_REDIRECT_URI=https://your-app.test/auth/google/callback
PKCE for SPAs: Enable for single-page apps to prevent code flow attacks:
Socialite::driver('google')->enablePKCE();
Stateless Tokens: Use for APIs without sessions:
$user = Socialite::driver('google')->stateless()->user();
Avoid Redundant Calls:
Cache the Socialite instance if used repeatedly in a request:
$socialite = Socialite::driver('github');
$user = $socialite->user();
Refresh Tokens:
Use refreshToken() for long-lived access:
$token = $user->token;
$refreshedToken = Socialite::driver('google')->refreshToken($token);
How can I help you explore Laravel packages today?