2026年1月4日 星期日

在本機Laravel 12 中實作 Google OAuth2 登入

    在 Laravel 12 中實現 SSO (Single Sign-On) 登入功能。
    一、安裝 Socialite 套件
        1.指令:composer require laravel/socialite

    二、建立 Google OAuth 憑證
        1.前往 Google Cloud Console
        2.建立新專案或選擇現有專案。

        3.在「API 與服務」>「OAuth 同意畫面」中,設定應用程式的基本資訊。

        4.在「憑證」分頁點擊「建立憑證」>「OAuth 用戶端 ID」。

        5.應用程式類型選擇「網頁應用程式」。
        6.設定重新導向 URI
            (1)已授權的 JavaScript 來源http://127.0.0.1:8000 (或你的本機網址)
            (2)已授權的重新導向 URIhttp://127.0.0.1:8000/auth/google/callback

        7.取得 Client ID 與 Client Secret。

    三、設定環境變數
    1.修改 .env 檔案
    2.將你的憑證加入環境變數:
    同時用 127.0.0.1localhost)之間跳轉,Session 會失效。
APP_URL=http://127.0.0.1:8000
    與
GOOGLE_CLIENT_ID=取得的Client ID
GOOGLE_CLIENT_SECRET=取得的Client Secret
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/auth/google/callback
    如下圖:
    3.修改 config/services.php
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
    如下圖:
    4.資料庫與模型準備
    你需要確保 users 資料表有欄位可以儲存 Google ID(或記錄此用戶是透過 Google 登入的)。
    (1).指令:php artisan make:migration add_google_id_to_users_table
    (2)編輯 database/migrations/xxxxxx_add_google_id_to_users_table.php
        Schema::table('users', function (Blueprint $table) {
            //
            $table->string('google_id')->nullable()->unique();
        });
    與
        Schema::table('users', function (Blueprint $table) {
            //
            $table->dropColumn(['google_id']);
        });
    如下圖:
    (3)指令:php artisan migrate

    5.實作 Controller 與 路由    
    (1).編輯routes/web.php
use App\Http\Controllers\SocialiteController;
    與
Route::get('/auth/google', [SocialiteController::class, 'redirectToGoogle'])->name('google.login');
Route::get('/auth/google/callback', [SocialiteController::class, 'handleGoogleCallback']);
Route::get('/dashboard', function () {
    $user = Auth::user();
    return "<h1>登入成功!</h1><p>歡迎回來,{$user->name}</p><img src='{$user->avatar}' />";
})->middleware(['auth']); // 確保只有登入者能看

    如下圖:

    (2).建立 Controller
    指令:php artisan make:controller SocialiteController
    編輯app\Http\Controllers\SocialiteController.php
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
    與
    //
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

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

        // 1. 先嘗試用 google_id 找,找不到再用 email 找
        $user = User::where('google_id', $googleUser->id)
                ->orWhere('email', $googleUser->email)
                ->first();

        if ($user) {
            // 2. 如果找到了,更新他的 google_id(補齊資料)
            $user->update([
                'google_id' => $googleUser->id,
            ]);
        } else {
            // 3. 真的完全沒看過這人才建立新的
            $user = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'google_id' => $googleUser->id,
                'password' => bcrypt(str()->random(16)),
            ]);
        }

        Auth::login($user);

        return redirect('/dashboard');
    }

    如下圖:

    6.
前端測試
    (1).編輯resources\views\welcome.blade.php
        <div class="flex items-center justify-center w-full transition-opacity opacity-100 duration-750 lg:grow starting:opacity-0">
            <a href="{{ route('google.login') }}" class="btn btn-google">
                使用 Google 帳號登入
            </a>
        </div>
    如下圖:

    (2)指令:php artisan serve
    即可看到 http://127.0.0.1:8000/



    



資料來源:




沒有留言:

張貼留言

在本機 laravel 12 ,上傳很多PDF,上傳之後可以自己排序,合併之後下載-方法二

系列文章: 1. 利用 laravel 12 做一個類似Google文件的簡單範例 2. 在本機Laravel 12 中實作 Google OAuth2 登入 3. 如何在 Laravel 12 使用 Gmail SMTP 寄信 4. 在本機Laravel 12 中實作 Face...