Впровадження Google OAuth аутентифікації для веб-сайтів
Google OAuth 2.0 — один з найпоширеніших способів авторизації. Інтегрується через стандартний OAuth2-флоу або Google Identity Services (GIS) — новий JS SDK для кнопки «Sign in with Google».
Реєстрація OAuth-клієнта
- Google Cloud Console → APIs & Services → Credentials
- Створити OAuth 2.0 Client ID типу Web application
- Додати Authorized redirect URIs:
https://example.com/auth/google/callback - Зберегти Client ID і Client Secret
Laravel Socialite
composer require laravel/socialite
// config/services.php
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
// routes/web.php
Route::get('/auth/google', [GoogleAuthController::class, 'redirect']);
Route::get('/auth/google/callback', [GoogleAuthController::class, 'callback']);
class GoogleAuthController extends Controller
{
public function redirect(): RedirectResponse
{
return Socialite::driver('google')
->scopes(['openid', 'profile', 'email'])
->redirect();
}
public function callback(): RedirectResponse
{
try {
$googleUser = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login')->withErrors(['google' => 'Помилка авторизації Google']);
}
$user = User::updateOrCreate(
['google_id' => $googleUser->getId()],
[
'name' => $googleUser->getName(),
'email' => $googleUser->getEmail(),
'email_verified_at' => now(),
'avatar' => $googleUser->getAvatar(),
]
);
Auth::login($user, remember: true);
return redirect()->intended('/dashboard');
}
}
Пов'язування з існуючим аккаунтом
Якщо користувач уже зареєстрований з тим же email через пароль — вирішіть, як об'єднати аккаунти:
// Ищемо по google_id
$user = User::where('google_id', $googleUser->getId())->first();
// Якщо немає — ищемо по email (пов'язуємо існуючий аккаунт)
if (!$user) {
$user = User::where('email', $googleUser->getEmail())->first();
if ($user) {
$user->update(['google_id' => $googleUser->getId()]);
} else {
$user = User::create([
'google_id' => $googleUser->getId(),
'name' => $googleUser->getName(),
'email' => $googleUser->getEmail(),
'email_verified_at' => now(),
]);
}
}
One Tap / Google Identity Services
Новий Google Identity Services SDK дозволяє показати One Tap popup без редиректу:
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="{{ config('services.google.client_id') }}"
data-callback="handleGoogleResponse"
data-auto_prompt="false">
</div>
<div class="g_id_signin" data-type="standard"></div>
// Верифікація id_token на сервері
use Google\Client as GoogleClient;
public function handleToken(Request $request): JsonResponse
{
$client = new GoogleClient(['client_id' => config('services.google.client_id')]);
$payload = $client->verifyIdToken($request->credential);
if (!$payload) {
return response()->json(['error' => 'Invalid token'], 401);
}
$user = User::updateOrCreate(
['google_id' => $payload['sub']],
['name' => $payload['name'], 'email' => $payload['email']]
);
Auth::login($user);
return response()->json(['redirect' => '/dashboard']);
}
Терміни
Стандартний OAuth2-флоу через Socialite — 1–2 дні. З One Tap та пов'язуванням аккаунтів — 2–3 дні.







