To implement GitHub login using Laravel Socialite, follow these steps:
Step 1: Install Laravel Socialite
In your terminal, run the following command to install the Socialite package:
composer require laravel/socialite
Step 2: Configure GitHub OAuth Credentials
Visit the GitHub Developer Settings (https://github.com/settings/developers), create a new OAuth application, and obtain the Client ID and Client Secret.
Step 3: Configure Services in Laravel
Open `config/services.php` and add the GitHub OAuth credentials:
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_REDIRECT_URI'),
],
Step 4: Create Routes
In your `routes/web.php`, create routes for social login:
Route::get('auth/github', 'Auth\SocialController@redirectToGitHub');
Route::get('auth/github/callback', 'Auth\SocialController@handleGitHubCallback');
Step 5: Create Controller
Generate a controller using the following command:
php artisan make:controller Auth/SocialController
In `Auth/SocialController.php`, implement the following methods:
use Laravel\Socialite\Facades\Socialite;
public function redirectToGitHub()
{
return Socialite::driver('github')->redirect();
}
public function handleGitHubCallback()
{
$user = Socialite::driver('github')->user();
// $user contains user details received from GitHub
// You can now authenticate the user or perform other actions
return redirect()->route('home'); // Redirect after successful login
}
Step 6: Update .env File
Add your GitHub OAuth credentials to your `.env` file:
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
GITHUB_REDIRECT_URI=http://your-app-url/auth/github/callback
Replace `your_github_client_id` and `your_github_client_secret` with your actual credentials.
Step 7: Implement Login Button
In your view, create a link/button to initiate the GitHub login process:
<a href="{{ url('auth/github') }}">Login with GitHub</a>
That's it! Users can now click the "Login with GitHub" link/button, and they will be redirected to GitHub for authentication. Upon successful authentication, they will be redirected back to your application with user data.
Remember to handle user data appropriately, possibly by creating a new user or authenticating an existing user in your database. Also, customize the redirection and user management as per your application's requirements.
0 Comments