DEV Community

Miller Juma
Miller Juma

Posted on • Edited on

Laravel Socialite

To get started with Socialite, use Composer to add the package to your project's dependencies:

bash composer require laravel/socialite

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file, and should use the key facebook, twitter, linkedin, google, github, gitlab or bitbucket, depending on the providers your application requires. For example:

'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => 'http://your-callback-url',
],
Enter fullscreen mode Exit fullscreen mode

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php
/**
*@author Miller Juma
**/

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('github')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('github')->user();

        // $user->token;
    }
}
Enter fullscreen mode Exit fullscreen mode

The redirect method takes care of sending the user to the OAuth provider, while the user method will read the incoming request and retrieve the user's information from the provider.

You will need to define routes to your controller methods:

use App\Http\Controllers\Auth\LoginController;

Route::get('login/github', [LoginController::class, 'redirectToProvider']);
Route::get('login/github/callback', [LoginController::class, 'handleProviderCallback']);
Enter fullscreen mode Exit fullscreen mode

Try it.Will be happy to help you out when stuck...

Top comments (0)