- Set up OAuth Consent Screen in Google Cloud Console:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Go to APIs & Services > Credentials.
- Click on “Create credentials” and select “OAuth client ID”.
- Choose “Web application” as the application type.
- Set the Authorized Redirect URI to
http://your-domain.com/auth/google/callback
. - Note down the Client ID and Client Secret generated after creating the OAuth client ID.
- Install Socialite Package: Run the following composer command to install Socialite package
composer require laravel/socialite
- Configure Socialite:
- Add your Google Client ID and Client Secret to your
.env
file:
- Add your Google Client ID and Client Secret to your
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://your-domain.com/auth/google/callback
- Create Routes: Add the following routes to your
routes/web.php
Route::get('/auth/google', 'Auth\LoginController@redirectToGoogle');
Route::get('/auth/google/callback', 'Auth\LoginController@handleGoogleCallback');
- Create Controller Methods: Create methods in your
Auth\LoginController
to handle Google login:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Socialite;
class LoginController extends Controller
{
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->user();
// Your logic to handle the user after authentication
}
}
- Use Google Driver: Use the
google
driver in yourconfig/services.php
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
- Test: Visit
/auth/google
in your browser, and you should be redirected to Google’s login page. After successful authentication, you’ll be redirected back to your application.
That’s it! You have now added Google login using Socialite in your Laravel application. Make sure to handle the user data returned by Google according to your application’s requirements
Leave a Reply