Overview

Socialite is Laravel’s package for handling OAuth authentication with popular social networks and services. It simplifies the process of authenticating users via third-party providers like Google, Facebook, GitHub, Twitter, and others.

Install Laravel Socialite

First, you need to install the package via Composer

composer require laravel/socialite

Configure Socialite:

Add the credentials for the OAuth providers you want to use in the config/services.php file. For example:

return [     
    'github' => [         
        'client_id' => env('GITHUB_CLIENT_ID'),         
        'client_secret' => env('GITHUB_CLIENT_SECRET'),         
        'redirect' => env('GITHUB_REDIRECT_URI'),     
    ],     
    'google' => [         
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
        ],

        // Add other providers as needed
        
    ];

Update your .env file with the credentials for each provider:

    GITHUB_CLIENT_ID=your_github_client_id
    GITHUB_CLIENT_SECRET=your_github_client_secret
    GITHUB_REDIRECT_URI=http://your-app-url/auth/github/callback
    GOOGLE_CLIENT_ID=your_google_client_id
    GOOGLE_CLIENT_SECRET=your_google_client_secret
    GOOGLE_REDIRECT_URI=http://your-app-url/auth/google/callback

Create Routes for Authentication:

Define routes for redirecting users to the provider and handling the callback.

    use Laravel\Socialite\Facades\Socialite;  
    Route::get('/auth/{provider}', function ($provider) {     
        return Socialite::driver($provider)->redirect(); 
    });  
    Route::get('/auth/{provider}/callback', function ($provider) {     
        $user = Socialite::driver($provider)->user();      
    
        // Handle user information here, e.g., save to database or log them in     
        
        dd($user); 
    });

Handle the User Information:

Socialite provides user information, including the user’s name, email, and a unique identifier (id). For example:

    $user = Socialite::driver('github')->user();  
    // Example data 
    $name = $user->getName(); 
    $email = $user->getEmail(); 
    $avatar = $user->getAvatar();  
    
    // Check if the user already exists in the database 
    $existingUser = User::where('email', $email)->first();  
    if ($existingUser) {     
        // Log in the existing user     
        Auth::login($existingUser); 
    } else {     
        // Create a new user and log them in     
        $newUser = User::create([         
            'name' => $name,         
            'email' => $email,         
            'password' => bcrypt(Str::random(24)), 
            // Generate a random password     
            ]);      
        Auth::login($newUser); 
    }

Protect Routes:

Once the user is authenticated, you can protect routes using middleware like auth.

    Route::middleware(['auth'])->group(function () {     
        Route::get('/dashboard', function () {         
            return view('dashboard');     
        }); 
    });

Customization:

  • If you need to customize the scopes or permissions, you can do so using scope():

        Socialite::driver('github')->scopes(['read:user'])->redirect();
    
  • To retrieve the “token” and “refresh token” (for services that require it):

        $user = Socialite::driver('google')->user(); 
        $token = $user->token; $refreshToken = $user->refreshToken; // if available
    

Summary Workflow

  1. User clicks the Login with {Provider} button.
  2. Redirect the user to the provider’s OAuth page.
  3. User logs in and authorizes the application.
  4. The provider redirects the user back to your application with an access token.
  5. Use Socialite to retrieve the user’s information and handle authentication in your app.

Thanks.