Laravel Socialite, Laravel framework için geliştirilmiş, OAuth tabanlı sosyal giriş (social login) işlemlerini basitleştiren resmi, birinci taraf bir pakettir. Google, Facebook, GitHub, Twitter, LinkedIn gibi popüler sosyal medya ve hizmet sağlayıcıları üzerinden kullanıcı kimlik doğrulamasını hızlı ve kolay bir şekilde entegre etmenizi sağlar.
Neden Kullanılır?
Manuel olarak OAuth 1.0 veya OAuth 2.0 akışlarını uygulamak, API anahtarları, gizli anahtarlar, yeniden yönlendirme URL'leri, durum parametreleri, token değişimi ve kullanıcı verisi çekme gibi birçok karmaşık adımı içerir. Bu süreç hem zaman alıcı hem de hataya açık olabilir. Socialite, bu karmaşıklığı soyutlayarak, temiz ve ifade edici bir API sunar, böylece geliştiriciler çekirdek uygulama mantığına odaklanabilir.
Temel Özellikler ve Çalışma Prensibi:
1. Basit Konfigürasyon: Sosyal sağlayıcıların kimlik bilgileri (client ID, client secret) `config/services.php` dosyası üzerinden kolayca yönetilir.
2. Yeniden Yönlendirme: Kullanıcı "[Sağlayıcı] ile Giriş Yap" düğmesine tıkladığında, Socialite kullanıcıyı sosyal sağlayıcının yetkilendirme sayfasına yönlendirmek için bir URL oluşturur.
3. Geri Çağırma (Callback) İşlemi: Kullanıcı sosyal sağlayıcıda yetkilendirme izni verdikten sonra, sağlayıcı kullanıcıyı uygulamanızın belirlediği geri çağırma URL'sine bir yetkilendirme kodu ile yönlendirir. Socialite, bu kodu bir erişim token'ı ile değiştirmeyi ve sağlayıcının API'sinden kullanıcının ayrıntılarını (ID, ad, e-posta, avatar vb.) çekmeyi otomatik olarak halleder.
4. Kullanıcı Bilgisi Alma: Başarılı bir geri çağırma sonrasında, Socialite sağlayıcıdan çekilen bilgileri içeren bir `Laravel\Socialite\Two\User` (veya `One\User` OAuth 1.0 için) nesnesi döndürür. Bu nesne ile uygulamanızda kullanıcıyı bulabilir, yeni bir kullanıcı oluşturabilir ve kimlik doğrulama işlemini tamamlayabilirsiniz.
Desteklenen Sağlayıcılar:
Socialite kutudan çıkar çıkmaz (out-of-the-box) birçok popüler sağlayıcıyı destekler:
* Facebook
* Twitter (OAuth 1.0)
* LinkedIn
* Google
* GitHub
* GitLab
* Bitbucket
* Slack
* Ve diğerleri...
Kurulum ve Kullanım:
1. `composer require laravel/socialite` komutu ile paketi kurun.
2. Sosyal sağlayıcıların kimlik bilgilerini `.env` dosyanıza ve `config/services.php` dosyanıza ekleyin.
3. Giriş başlatma ve geri çağırma için rotalar tanımlayın.
4. Rotaları işlemek için bir kontrolcü oluşturun, burada Socialite'ı kullanarak yeniden yönlendirme ve kullanıcı verilerini alma mantığını uygulayın.
Özetle, Laravel Socialite, modern web uygulamalarında vazgeçilmez bir özellik olan sosyal giriş entegrasyonunu Laravel geliştiricileri için son derece kolay ve güvenli hale getirir.
Example Code
```php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class SocialAuthController extends Controller
{
/
* Redirect the user to the provider authentication page.
*
* @param string $provider
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function redirectToProvider(string $provider)
{
// Ensure the provider is configured in config/services.php
// Example: 'github' => ['client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => env('GITHUB_REDIRECT_URI')]
return Socialite::driver($provider)->redirect();
}
/
* Obtain the user information from the provider.
*
* @param string $provider
* @return \Illuminate\Http\RedirectResponse
*/
public function handleProviderCallback(string $provider): RedirectResponse
{
try {
// Retrieve user details from the social provider
$socialiteUser = Socialite::driver($provider)->user();
// Check if a user with this social ID already exists
$user = User::where('provider_id', $socialiteUser->getId())
->where('provider_name', $provider)
->first();
if ($user) {
// If user exists, log them in
Auth::login($user);
return redirect('/dashboard'); // Or wherever you want to redirect
} else {
// If user doesn't exist, create a new user
// You might want to check for existing email or handle duplicate emails
$existingUser = User::where('email', $socialiteUser->getEmail())->first();
if ($existingUser) {
// If an existing user has this email but hasn't linked this provider yet,
// you might want to link the provider to their existing account.
// For simplicity, this example creates a new user if email is not found or is null.
// In a real app, you'd likely want to merge or prompt the user.
return redirect('/login')->withErrors(['social_login' => 'An account with this email already exists. Please login normally or link your social account.']);
}
$user = User::create([
'name' => $socialiteUser->getName() ?? $socialiteUser->getNickname() ?? 'User',
'email' => $socialiteUser->getEmail(),
'provider_id' => $socialiteUser->getId(),
'provider_name' => $provider,
'avatar' => $socialiteUser->getAvatar(),
'email_verified_at' => now(), // Assume email is verified by social provider
'password' => bcrypt(str()->random(16)), // Assign a random password, not used for social login
]);
Auth::login($user);
return redirect('/dashboard');
}
} catch (\Exception $e) {
// Log the error for debugging purposes
logger()->error('Socialite authentication failed: ' . $e->getMessage(), ['provider' => $provider]);
return redirect('/login')->withErrors(['social_login' => 'Unable to authenticate with ' . ucfirst($provider) . '. Please try again.']);
}
}
}
// --- Minimal Configuration (`.env`) ---
// GITHUB_CLIENT_ID=your-github-client-id
// GITHUB_CLIENT_SECRET=your-github-client-secret
// GITHUB_REDIRECT_URI=http://localhost:8000/auth/github/callback
// --- Minimal Configuration (`config/services.php`) ---
// 'github' => [
// 'client_id' => env('GITHUB_CLIENT_ID'),
// 'client_secret' => env('GITHUB_CLIENT_SECRET'),
// 'redirect' => env('GITHUB_REDIRECT_URI'),
// ],
// --- Minimal Routes (`routes/web.php`) ---
// use App\Http\Controllers\Auth\SocialAuthController;
// Route::get('/auth/{provider}', [SocialAuthController::class, 'redirectToProvider'])->name('social.auth');
// Route::get('/auth/{provider}/callback', [SocialAuthController::class, 'handleProviderCallback']);
// --- User Model (`app/Models/User.php`) ---
// Add these fillable properties to your User model:
// protected $fillable = [
// 'name', 'email', 'password', 'provider_id', 'provider_name', 'avatar', 'email_verified_at'
// ];
// --- Migration (Example for adding social fields to users table) ---
// Schema::table('users', function (Blueprint $table) {
// $table->string('provider_id')->nullable()->after('password');
// $table->string('provider_name')->nullable()->after('provider_id');
// $table->string('avatar')->nullable()->after('provider_name');
// $table->index(['provider_id', 'provider_name']);
// });
```








laravel/socialite