Google

Google là một công cụ tìm kiếm trên internet. Nó sử dụng một thuật toán độc quyền được thiết kế để truy xuất và sắp xếp các kết quả tìm kiếm nhằm cung cấp các nguồn dữ liệu đáng tin cậy và phù hợp nhất có thể.

Sứ mệnh đã nêu của Google là “tổ chức thông tin của thế giới và làm cho thông tin đó có thể truy cập và hữu ích trên toàn cầu”.

Google chiếm ưu thế đến mức thuật ngữ “Google” cũng có thể được sử dụng như một động từ, do đó khi ai đó tìm kiếm thứ gì đó trên Google, họ có thể nói rằng họ “Googled” nó.

Thực hiện chức năng Login Google trong Laravel

Ngoài xác thực dựa trên biểu mẫu điển hình, Laravel cũng cung cấp một cách đơn giản và thuận tiện đó là sử dụng Laravel Socialite để xác thực với các nhà cung cấp OAuth.

Laravel Socialite hiện hỗ trợ xác thực qua các nhà cung cấp OAuth như: Facebook, Twitter, LinkedIn, Google, GitHub, GitLab và Bitbucket.

Trong bài viết này, tôi sẽ hướng dẫn các bạn cách sử dụng Laravel Socialite để thực hiện đăng nhập qua Google.

Google Client ID and Secret

Bước 1: Đăng nhập Google và truy cập trang Google Developers Console.

Bước 2: Nhấn nút OAuth consent screen, sau đó chọn option External và nhấn nút Create:

Bước 3: Nhập thông tin App name, User support email, Developer contact information và nhấn nút Save and continue:

Bước 4: Trong mục Scopes, bạn có thể chỉ định phạm vi yêu cầu quyền từ người dùng để ứng dụng của bạn có thể truy cập vào dữ liệu người dùng từ tài khoản Google của họ:

Nếu không có gì đăc biệt, bạn có thể nhấn nút Save and continue để đến màn hình tiếp theo.

Bước 5: Trong mục Test users, bạn có thể thêm User trong quá trình kiểm thử, sau đó nhấn nút Save and continue:

Bước 6: Nhấn nút Credentials, sau đó tiếp tục nhấn nút CREATE CREDENTIALS và chọn mục OAuth client ID:

Bước 7: Ở màn hình Create OAuth client ID  ở mục Application Type bạn hãy chọn Web application và nhập thông tin Name:

Bước 8: Thêm URL mục Authorized JavaScript originsAuthorized redirect URIs:

Bước 9: Nhấn nút Create và chờ đợi trong vài phút, chúng ta sẽ nhận được Client ID  và Client Secret như sau:

Cài đặt chức năng Login Google trong Laravel

Khởi tạo dự án Laravel

Đầu tiên, chúng ta sẽ khởi tạo dự án Laravel mới. Bạn có thể làm điều này bằng cách sử dụng lệnh sau:

composer create-project --prefer-dist laravel/laravel laravel_socialite

Bước tiếp theo, chúng ta sẽ tiến hành kết nối đến cơ sở dữ liệu bằng cách chỉnh sửa các thông tin sau trong tập tin .env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socialite
DB_USERNAME=root
DB_PASSWORD=

Cài đặt Jetstream trong Laravel

Đầu tiên, để bắt đầu, chúng ta cần cài đặt thư viện Jetstream bằng cách chạy lệnh sau:

composer require laravel/jetstream

Tiếp theo, chúng ta tiến hành cài đặt Jetstream với Livewire bằng lệnh sau:

php artisan jetstream:install livewire

Sau khi cài đặt Jetstream, bạn cần tiến hành cài đặt và build NPM dependencies và thực hiện migrate cơ sở dữ liệu:

npm install && npm run build && php artisan migrate

Cài đặt Socialite trong Laravel

Đầu tiên, để tích hợp tính năng xác thực với nhà cung cấp OAuth, chúng ta sẽ cài đặt thư viện Socialite bằng lệnh sau:

composer require laravel/socialite

Chúng ta sẽ thêm thông tin OAuth của Google vào Laravel, những thông tin xác thực này sẽ được đặt tập tin config/services.php:

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_CLIENT_REDIRECT'),
],

Tiếp theo, chúng ta cần chỉnh sửa cấu trúc bảng users để có thể lưu các thông tin Google vào hệ thống bằng lệnh sau:

php artisan make:migration add_google_to_users_table --table=users

Sau đó, hãy chỉnh sửa nội dung migrate trên trong thư mục database/migrations như sau:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id');
            $table->string('google_token');
            $table->string('google_refresh_token')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('google_id');
            $table->dropColumn('google_token');
            $table->dropColumn('google_refresh_token');
        });
    }
};

Sau khi chỉnh sửa migrate, chúng ta sẽ chạy lệnh sau để chỉnh sửa cấu trúc bảng users:

php artisan migrate

Sau đó, chúng ta sẽ thêm các Column của Google vào $fillable của Model User trong thư mục app/Models như sau:

<?php
namespace App\Models;
...
class User extends Authenticatable
{
   ...
    protected $fillable = [
        ...
        'google_id',
        'google_token',
        'google_refresh_token',
    ];
    ...
}

Tiếp theo, chúng ta sẽ tạo một  Controller sẽ thực hiện xử lý đăng nhập Google bằng lệnh sau:

php artisan make:controller SocialAuthController

Sau khi chạy lệnh trên xong, hãy chỉnh sửa tập tin SocialAuthController.php trong thư mục app/Http/Controllers với nội dung như sau:

<?php

namespace App\Http\Controllers;

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

class SocialAuthController extends Controller
{
    public function redirectToProvider($provider)
    {
        try {
            return Socialite::driver($provider)->redirect();
        } catch (Throwable $th) {
            report($th);
            return redirect()->route('login');
        }
    }

    public function handleProviderCallback($provider)
    {
        $user = self::createOrGetUser($provider);
        if ($user) {
            Auth::login($user);
            return redirect()->route('dashboard');
        }
        return redirect()->route('login');
    }

    public function createOrGetUser($provider)
    {
        try {
            $google_user = Socialite::driver($provider)->user();
            return  User::updateOrCreate([
                'google_id' => $google_user->id,
            ], [
                'name'                 => $google_user->name,
                'email'                => $google_user->email,
                'google_token'         => $google_user->token,
                'google_refresh_token' => $google_user->refreshToken,
                'password'             => Hash::make('ManhDanBlogs') // Lưu ý: Bạn nên thay đổi thành password ngẫu nhiên để tăng tính bảo mật.
            ]);
        } catch (Throwable $th) {
            report($th);
            return false;
        }
    }
}

Chúng ta hãy thiết lập route cho hàm redirectToProvider và handleProviderCallback trong SocialAuthController.php trong tập tin routes/web.php như sau:

<?php

...
use App\Http\Controllers\SocialAuthController;
...
Route::get('auth/{social}', [SocialAuthController::class, 'redirectToProvider'])->name('social_redirect');
Route::get('auth/{social}/callback', [SocialAuthController::class, 'handleProviderCallback'])->name('social_callback');

Tiếp theo, chúng ta hãy thêm Client ID and Secret key của Github mà bạn đã tạo ở trên vào tập tin .env của dự án Laravel:

GOOGLE_CLIENT_ID=xxxxx
GOOGLE_CLIENT_SECRET=xxxxx
GOOGLE_CLIENT_REDIRECT=https://laravel-socialite.manhdan.dev/auth/google/callback

Cuối cùng, chúng ta hãy chỉnh sửa tập tin login.blade.php trong thư mục views/auth với nội dung như sau:

<x-guest-layout>
    <x-authentication-card>
        <x-slot name="logo">
            <x-authentication-card-logo />
        </x-slot>

        <x-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-label for="email" value="{{ __('Email') }}" />
                <x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus autocomplete="username" />
            </div>

            <div class="mt-4">
                <x-label for="password" value="{{ __('Password') }}" />
                <x-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <x-checkbox id="remember_me" name="remember" />
                    <span class="ms-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-button class="ms-4">
                    {{ __('Log in') }}
                </x-button>
            </div>

            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ route('social_redirect', ['social' => 'google']) }}"
                    style="background: #ea4335; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:3px;">
                    Login with Google
                </a>
            </div>

        </form>
    </x-authentication-card>
</x-guest-layout>

Kết quả của công việc bạn đã làm đang chờ bạn khám phá!

Sau khi đã hoàn thành các bước trên, giờ là lúc để chúng ta sẽ cùng nhau khám phá thành quả công sức của mình.

Chúng ta sẽ tiến hành đăng nhập vào trang Laravel, và địa chỉ truy cập cụ thể như sau trong bài viết này:

https://laravel-socialite.manhdan.dev/login

Đây chính là thành quả của chúng ta sau khi thực hiện các bước ở phía trên 🤤🤤🤤🏆🍨🍨🍨.


CÓ THỂ BẠN QUAN TÂM

Integrating elFinder Into CKEditor 5 In Laravel

Integrating elFinder Into CKEditor 5 In Laravel

CKEditor 5 CKEditor 5 là một trình soạn thảo văn bản phong phú JavaScript với nhiều tính năng và khả năng tùy chỉnh. CKEditor 5 có kiến trúc MVC hiện đại, mô hình dữ liệu tùy chỉnh và DOM ảo, mang...

Efficient Laravel PDF Export for Large Datasets

Efficient Laravel PDF Export for Large Datasets

Xuất file PDF là một tính năng quan trọng của nhiều ứng dụng web, đặc biệt là các trang thương mại điện tử, giúp người dùng tạo và lưu trữ các bản báo cáo, hóa đơn, v.v.  Tuy nhiên, khi phải xử lý...

Laravel Artisan Console

Laravel Artisan Console

Ngoài các lệnh command mặc định của Laravel được cung cấp bởi Artisan, có rất nhiều tác vụ trong ứng dụng Laravel của bạn có thể được xử lý rất tốt bằng các lệnh command này. Nhưng đôi khi có nhiều tá...

Document Laravel API With OpenAPI (Swagger)

Document Laravel API With OpenAPI (Swagger)

Swagger là gì? Swagger là một Ngôn ngữ mô tả giao diện để mô tả các API RESTful được thể hiện bằng JSON. Swagger được sử dụng cùng với một bộ công cụ phần mềm mã nguồn mở để thiết kế, xây dựng, l...

Laravel Has Many Through Eloquent Relationship

Laravel Has Many Through Eloquent Relationship

Has Many Through Relationship hơi phức tạp để hiểu một cách đơn giản, nó sẽ cung cấp cho chúng ta một con đường tắt để có thể truy cập dữ liệu của một quan hệ xa xôi thông qua một mối quan hệ trung gi...

Cloudflare's Turnstile CAPTCHA in Laravel

Cloudflare's Turnstile CAPTCHA in Laravel

Ngày 28/09/2022, Cloudflare đã thông báo về phiên bản beta mở của Turnstile, một giải pháp thay thế vô hình cho CAPTCHA. Bất kỳ ai, ở bất kỳ đâu trên Internet muốn thay thế CAPTCHA trên trang web c...

Send Slack Notifications In Laravel

Send Slack Notifications In Laravel

Slack là gì? Slack là một công cụ giao tiếp tại nơi làm việc, "một nơi duy nhất cho các tin nhắn, công cụ và file." Điều này có nghĩa là Slack là một hệ thống nhắn tin tức thì với nhiều plug-in cho...

Laravel UI Password Reset Expired

Laravel UI Password Reset Expired

Trong thư viện laravel/ui, thì chức năng password reset dù cho token có hết hạn thì vẫn có truy cập vào trang password reset, đến khi bạn submit form thì mới thông báo là token đã hết hạn. Nhưng có mộ...

Laravel Routing

Laravel Routing

Route là gì? Đúng như tên gọi của nó, Route thực hiện chức năng định tuyến, dẫn đường cho các HTTP request gửi đến đúng nơi mà ta mong muốn. Với sự phát triển mạnh mẽ của ứng dụng web ngày nay, việc...

ManhDanBlogs