Laravel Socialite is a Laravel package that provides a convenient way to authenticate with OAuth providers. It simplifies the process of integrating third-party authentication services such as Facebook, Twitter, Google, GitHub, and others into your Laravel application.
Here are the general steps to use Laravel Socialite for third-party authentication:
You can install Laravel Socialite using Composer. Open your terminal and run the following command:
bashcomposer require laravel/socialite
After installing Socialite, you need to set up OAuth credentials for the providers you want to use. Open your config/services.php
file and add the following configuration for the desired providers:
php'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_REDIRECT_URI'),
],
// Add configurations for other providers as needed
In your routes/web.php
file, define routes for handling the authentication process:
phpRoute::get('/login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('/login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');
Create a new controller or use an existing one to handle authentication. In this example, let's use the LoginController
.
bashphp artisan make:controller Auth\LoginController
In the LoginController
, add the following methods:
phpuse Laravel\Socialite\Facades\Socialite;
class LoginController extends Controller
{
// Redirect the user to the OAuth provider
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
// Obtain the user information from the provider
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
// Your application logic here (e.g., log in the user)
return redirect('/home');
}
}
Make sure to add the corresponding environment variables for the OAuth credentials in your .env
file:
envGITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GITHUB_REDIRECT_URI=http://your-app-url/login/github/callback
Now, you can visit the /login/{provider}
route in your application to initiate the authentication process with the selected provider.
Remember to adapt the code according to your specific needs and integrate it into your user authentication flow.
Note: The steps might vary slightly depending on your Laravel version, so be sure to check the official Laravel Socialite documentation for the version you are using.
=== Happy Coding :)