0

Cách Implement Google Login trong Laravel

Google Login cho phép người dùng đăng nhập vào ứng dụng Laravel của bạn bằng tài khoản Google. Điều này giúp đơn giản hóa quá trình đăng nhập và tăng cường bảo mật bằng cách giảm thiểu việc sử dụng mật khẩu truyền thống.

Điều kiện tiên quyết

Bước 1: Cài đặt thông tin xác thực Google OAuth

  • Truy cập vào Google Cloud Console: https://console.cloud.google.com/
  • Tạo một dự án mới hoặc chọn một dự án hiện có.
  • Điều hướng đến APIs & Services > Credentials.
  • Nhấn vào Create Credentials > OAuth Client ID.
  • Chọn Web application làm loại ứng dụng.
  • Trong "Authorized Redirect URIs", thêm:
   http://127.0.0.1:8000/auth/google/callback
  • Nhấn Create, rồi sao chép Client ID và Client Secret.

Bước 2: Cài đặt Laravel Socialite

Socialite là gói chính thức của Laravel để xử lý xác thực OAuth.

Chạy lệnh sau để cài đặt gói Socialite:

composer require laravel/socialite

Bước 3: Cấu hình Google OAuth trong Laravel

Thêm thông tin xác thực Google vào file .env:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/auth/google/callback

Sau đó, thêm cấu hình Socialite vào config/services.php:

return [
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
];

Bước 4: Tạo các route cho Google Login

Thêm các route sau vào routes/web.php:

use App\Http\Controllers\GoogleController;

Route::get('/auth/google', [GoogleController::class, 'redirectToGoogle'])->name('google.login');
Route::get('/auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);

Bước 5: Tạo Google Authentication Controller

Chạy lệnh sau để tạo controller:

php artisan make:controller GoogleController

Sau đó, cập nhật app/Http/Controllers/GoogleController.php với logic xác thực Google.

namespace App\Http\Controllers;

use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class GoogleController extends Controller
{
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();

            // Check if a user with this email exists
            $user = User::where('email', $googleUser->email)->first();

            if (!$user) {
                // Create a new user if not found
                $user = User::create([
                    'first_name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id' => $googleUser->id,
                    'password' => bcrypt(uniqid()), // Random hashed password
                ]);
            }

            // Log in the user
            Auth::login($user);
            return redirect()->route('dashboard')->with('success', 'Login successful!');
        } catch (Exception $e) {
            return redirect()->route('login')->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }
}

Bước 6: Thêm nút Google Login vào View

Trong trang đăng nhập của bạn (ví dụ: resources/views/auth/login.blade.php), thêm nút Google Login:

<a href="{{ route('google.login') }}" class="btn btn-danger">Login with Google</a>

Bước 7: Kiểm tra tích hợp

  • Khởi động máy chủ phát triển Laravel:
   php artisan serve
  • Mở http://127.0.0.1:8000/login và nhấn vào "Login with Google."
  • Đăng nhập bằng tài khoản Google của bạn.
  • Nếu mọi thứ được cấu hình đúng, người dùng sẽ được đăng nhập và chuyển hướng đến dashboard.

Kết luận

Bạn đã triển khai thành công Google Login trong ứng dụng Laravel của mình sử dụng Socialite. Phương pháp này tăng cường bảo mật và cải thiện trải nghiệm người dùng bằng cách cho phép xác thực mà không cần sử dụng mật khẩu.


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.