Laravel Socialite: OAuth Authentication
Laravel Socialite: OAuth Authentication
Laravel Socialite: OAuth Authentication
Tip: Install Socialite
composer require laravel/socialite
Gotcha: Configure Provider
'services' => [
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => '/auth/github/callback',
],
],
Tip: Redirect to Provider
return Socialite::driver('github')->redirect();
Gotcha: Handle Callback
$user = Socialite::driver('github')->user();
Tip: Find or Create User
$localUser = User::updateOrCreate(
['email' => $user->email],
['name' => $user->name, 'github_id' => $user->id]
);
Gotcha: Stateless Providers
Socialite::driver('github')->stateless()->user();
For APIs where you can't maintain session state.
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
Social authentication via Socialite is convenient, but the security edge cases are unforgiving. I've debugged incidents where account takeover was possible because the email returned by OAuth wasn't verified — an attacker could register an unverified email on a provider and link it to an existing account. Always verify that the email from the OAuth provider is confirmed before linking accounts. Also, handle the case where the email changes: don't silently update it in your database.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)