Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Laravel Socialite
https://github.com/laravel/socialite
Admin
Laravel wrapper around OAuth 1 & OAuth 2 libraries.
Tokens:
264
Snippets:
4
Trust Score:
9.5
Update:
4 months ago
Context
Skills
Chat
Benchmark
9
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel Socialite Laravel Socialite provides an expressive, fluent interface to OAuth authentication with multiple social platforms including Facebook, Twitter, Google, LinkedIn, GitHub, GitLab, Bitbucket, and Slack. This package eliminates the complexity of implementing OAuth flows by providing a unified API across different providers, handling token exchange, user data retrieval, and state verification automatically. Built on top of OAuth 1 and OAuth 2 client libraries, Socialite integrates seamlessly with Laravel's service container and configuration system. It supports both stateful (session-based) and stateless authentication, PKCE for enhanced security, custom scopes, and flexible redirect handling. The package is designed to be extended with custom providers while maintaining a consistent interface across all implementations. ## Redirect User to OAuth Provider Initiate the OAuth authentication flow by redirecting users to the provider's authorization page. ```php use Laravel\Socialite\Facades\Socialite; // In your controller Route::get('/auth/redirect', function () { return Socialite::driver('github')->redirect(); }); // With custom scopes Route::get('/auth/google', function () { return Socialite::driver('google') ->scopes(['profile', 'email', 'openid']) ->redirect(); }); // Stateless authentication (for APIs) Route::get('/auth/facebook', function () { return Socialite::driver('facebook')->stateless()->redirect(); }); ``` ## Retrieve Authenticated User Data Handle the OAuth callback and retrieve the authenticated user's information from the provider. ```php use Laravel\Socialite\Facades\Socialite; use Illuminate\Support\Facades\Auth; Route::get('/auth/callback', function () { try { $socialiteUser = Socialite::driver('github')->user(); // Access user properties $providerId = $socialiteUser->getId(); // "12345678" $nickname = $socialiteUser->getNickname(); // "johndoe" $name = $socialiteUser->getName(); // "John Doe" $email = $socialiteUser->getEmail(); // "john@example.com" $avatar = $socialiteUser->getAvatar(); // "https://..." // Access OAuth tokens $token = $socialiteUser->token; $refreshToken = $socialiteUser->refreshToken; $expiresIn = $socialiteUser->expiresIn; // Find or create user in your database $user = User::updateOrCreate( ['email' => $socialiteUser->getEmail()], [ 'name' => $socialiteUser->getName(), 'github_id' => $socialiteUser->getId(), 'github_token' => $socialiteUser->token, 'avatar' => $socialiteUser->getAvatar(), ] ); Auth::login($user); return redirect('/dashboard'); } catch (\Laravel\Socialite\Two\InvalidStateException $e) { return redirect('/auth/redirect'); } }); ``` ## Retrieve User from Existing Token Skip the OAuth flow and retrieve user data directly using a previously obtained access token. ```php use Laravel\Socialite\Facades\Socialite; Route::get('/api/user', function () { $token = request()->bearerToken(); $socialiteUser = Socialite::driver('github')->userFromToken($token); return response()->json([ 'id' => $socialiteUser->getId(), 'name' => $socialiteUser->getName(), 'email' => $socialiteUser->getEmail(), 'avatar' => $socialiteUser->getAvatar(), ]); }); // For OAuth 1.0 providers (Twitter) Route::get('/api/twitter-user', function () { $token = 'oauth_token_from_database'; $tokenSecret = 'oauth_token_secret_from_database'; $socialiteUser = Socialite::driver('twitter') ->userFromTokenAndSecret($token, $tokenSecret); return response()->json([ 'id' => $socialiteUser->getId(), 'nickname' => $socialiteUser->getNickname(), ]); }); ``` ## Configure OAuth Providers Set up provider credentials and callback URLs in your Laravel configuration. ```php // config/services.php return [ 'github' => [ 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => env('GITHUB_REDIRECT_URL', '/auth/github/callback'), ], 'google' => [ 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'), 'redirect' => '/auth/google/callback', ], 'facebook' => [ 'client_id' => env('FACEBOOK_CLIENT_ID'), 'client_secret' => env('FACEBOOK_CLIENT_SECRET'), 'redirect' => '/auth/facebook/callback', ], 'twitter' => [ 'client_id' => env('TWITTER_CLIENT_ID'), 'client_secret' => env('TWITTER_CLIENT_SECRET'), 'redirect' => '/auth/twitter/callback', 'oauth' => 2, // Use OAuth 2.0 (omit for OAuth 1.0) ], 'gitlab' => [ 'client_id' => env('GITLAB_CLIENT_ID'), 'client_secret' => env('GITLAB_CLIENT_SECRET'), 'redirect' => '/auth/gitlab/callback', 'host' => 'https://gitlab.example.com', // For self-hosted GitLab ], ]; ``` ## Customize Scopes and Parameters Request specific permissions and pass additional parameters to the OAuth provider. ```php use Laravel\Socialite\Facades\Socialite; // Add scopes to existing defaults Route::get('/auth/github', function () { return Socialite::driver('github') ->scopes(['repo', 'gist', 'user:email']) ->redirect(); }); // Replace all scopes Route::get('/auth/google', function () { return Socialite::driver('google') ->setScopes(['openid', 'email', 'profile']) ->redirect(); }); // Pass custom parameters to provider Route::get('/auth/facebook', function () { return Socialite::driver('facebook') ->with(['display' => 'popup', 'auth_type' => 'rerequest']) ->redirect(); }); // Facebook-specific methods Route::get('/auth/facebook-custom', function () { return Socialite::driver('facebook') ->fields(['name', 'email', 'first_name', 'last_name']) ->scopes(['email', 'public_profile', 'user_friends']) ->asPopup() ->reRequest() ->redirect(); }); ``` ## Use PKCE for Enhanced Security Enable Proof Key for Code Exchange to protect against authorization code interception attacks. ```php use Laravel\Socialite\Facades\Socialite; Route::get('/auth/secure', function () { return Socialite::driver('google') ->enablePKCE() ->redirect(); }); // PKCE is automatically validated during callback Route::get('/auth/secure/callback', function () { $user = Socialite::driver('google')->user(); // PKCE verification happens automatically return response()->json($user); }); ``` ## Build Custom Provider Create custom OAuth providers by extending the AbstractProvider class. ```php namespace App\Auth; use Laravel\Socialite\Two\AbstractProvider; use Laravel\Socialite\Two\User; use GuzzleHttp\RequestOptions; class CustomProvider extends AbstractProvider { protected $scopes = ['read_user']; protected $scopeSeparator = ' '; protected function getAuthUrl($state) { return $this->buildAuthUrlFromBase( 'https://oauth.example.com/authorize', $state ); } protected function getTokenUrl() { return 'https://oauth.example.com/token'; } protected function getUserByToken($token) { $response = $this->getHttpClient()->get( 'https://api.example.com/user', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', ], ] ); return json_decode($response->getBody(), true); } protected function mapUserToObject(array $user) { return (new User)->setRaw($user)->map([ 'id' => $user['id'], 'nickname' => $user['username'], 'name' => $user['full_name'], 'email' => $user['email'], 'avatar' => $user['profile_image_url'], ]); } } // Register in service provider use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function boot() { $socialite = $this->app->make(\Laravel\Socialite\Contracts\Factory::class); $socialite->extend('custom', function ($app) use ($socialite) { $config = $app['config']['services.custom']; return $socialite->buildProvider(CustomProvider::class, $config); }); } } // Use custom provider Route::get('/auth/custom', function () { return Socialite::driver('custom')->redirect(); }); ``` ## Stateless API Authentication Implement OAuth authentication for stateless APIs without session storage. ```php use Laravel\Socialite\Facades\Socialite; // API route for initiating OAuth (returns URL instead of redirect) Route::post('/api/auth/url', function () { $authUrl = Socialite::driver('github') ->stateless() ->redirect() ->getTargetUrl(); return response()->json(['auth_url' => $authUrl]); }); // API callback handler Route::get('/api/auth/callback', function () { try { $socialiteUser = Socialite::driver('github') ->stateless() ->user(); // Create or update user $user = User::firstOrCreate( ['provider_id' => $socialiteUser->getId()], [ 'name' => $socialiteUser->getName(), 'email' => $socialiteUser->getEmail(), ] ); // Generate API token $apiToken = $user->createToken('oauth-token')->plainTextToken; return response()->json([ 'access_token' => $apiToken, 'token_type' => 'Bearer', 'user' => $user, ]); } catch (\Exception $e) { return response()->json(['error' => 'Authentication failed'], 401); } }); ``` ## Handle Multiple Providers Manage authentication across multiple OAuth providers with a unified interface. ```php use Laravel\Socialite\Facades\Socialite; Route::get('/auth/{provider}', function ($provider) { $allowedProviders = ['github', 'google', 'facebook', 'twitter']; if (!in_array($provider, $allowedProviders)) { abort(404); } return Socialite::driver($provider)->redirect(); }); Route::get('/auth/{provider}/callback', function ($provider) { $socialiteUser = Socialite::driver($provider)->user(); $user = User::firstOrCreate( ['email' => $socialiteUser->getEmail()], ['name' => $socialiteUser->getName()] ); // Store provider-specific data $user->socialAccounts()->updateOrCreate( [ 'provider' => $provider, 'provider_id' => $socialiteUser->getId(), ], [ 'token' => $socialiteUser->token, 'refresh_token' => $socialiteUser->refreshToken, 'expires_at' => $socialiteUser->expiresIn ? now()->addSeconds($socialiteUser->expiresIn) : null, ] ); Auth::login($user); return redirect('/dashboard'); }); ``` ## Access Raw Provider Response Access the complete raw response from OAuth providers for additional data. ```php use Laravel\Socialite\Facades\Socialite; Route::get('/auth/callback', function () { $socialiteUser = Socialite::driver('github')->user(); // Access raw provider data $rawUser = $socialiteUser->getRaw(); // GitHub-specific fields $bio = $rawUser['bio'] ?? null; $company = $rawUser['company'] ?? null; $location = $rawUser['location'] ?? null; $publicRepos = $rawUser['public_repos'] ?? 0; // Array access is also supported $nodeId = $socialiteUser['node_id']; $htmlUrl = $socialiteUser['html_url']; // Google-specific fields if ($rawUser['email_verified'] ?? false) { // Email is verified } $locale = $rawUser['locale'] ?? 'en'; $picture = $rawUser['picture'] ?? null; return response()->json([ 'standard' => [ 'id' => $socialiteUser->getId(), 'email' => $socialiteUser->getEmail(), ], 'provider_specific' => $rawUser, ]); }); ``` ## Summary Laravel Socialite streamlines OAuth integration across web applications and APIs by providing a consistent interface for multiple social authentication providers. The primary use cases include implementing "Login with Google/GitHub/Facebook" functionality, building social media integration features, and enabling API authentication through OAuth tokens. Applications can use Socialite for both traditional session-based authentication and modern stateless API authentication patterns. The package integrates seamlessly with Laravel's ecosystem through service providers, facades, and configuration files. Its fluent API allows developers to customize scopes, enable security features like PKCE, handle multiple providers simultaneously, and extend functionality with custom OAuth providers. With minimal configuration and a few lines of code, applications can implement production-ready social authentication while maintaining full control over user data storage, token management, and error handling.