[Laravel Socialite] 5 bước hướng dẫn Laravel Socialite tích hợp xác thực Google vào website

Đăng bởi: Admin | Lượt xem: 2350 | Chuyên mục: Laravel

Trong bài này chúng ta tiếp tục tìm hiểu cách sử dụng Laravel Socialite để tích hợp xác thực Google qua 5 bước đơn giản.


Tích hợp các mạng xã hội vào phần đăng nhập hệ thống website đang trở lên phổ biến do có nhiều các lợi ích như:

  • Tăng trải nghiệm người dùng: việc đăng ký tài khoản mới và đăng nhập đơn giản hơn rất nhiều do bản thân các tài khoản mạng xã hội đã tự xác thực.
  • Thu thập thêm thông tin người dùng như ngày sinh, nơi sinh sống, giới tính... những thông tin này chúng ta thường rút gọn trong quá trình đăng ký tài khoản.
  • Kết hợp với các hệ thống bình luận sử dụng mạng xã hội rất thuận tiện.

Chúng ta sẽ thực hiện theo các bước sau

  • Bước 1: Cài đặt Laravel Socialite (Tùy chọn, nếu đã cài đặt có thể bỏ qua)

    Chúng ta sử dụng gói Laravel Socialite cho việc tích hợp, cài đặt gói này bằng lệnh composer như sau:

    c:\xampp\htdocs\laravel-test>composer require laravel/socialite
    Using version ^3.0 for laravel/socialite
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Package operations: 2 installs, 0 updates, 0 removals
      - Installing league/oauth1-client (1.7.0): Loading from cache
      - Installing laravel/socialite (v3.0.5): Loading from cache
    Writing lock file
    Generating autoload files
    > Illuminate\Foundation\ComposerScripts::postUpdate
    > php artisan optimize
    Generating optimized class loader
    The compiled services file has been removed.

    Tiếp theo cấu hình Laravel Socialite trong config/app.php:

    ...
    'providers' => [
        ...
        Laravel\Socialite\SocialiteServiceProvider::class,
    ],
    'aliases' => [
        ...
        'Socialite' => Laravel\Socialite\Facades\Socialite::class,
    ],

    Bước 2: Cài đặt tài khoản Google

    Mở Google Developers Console và chọn menu Credentials và chọn OAuth consent screen

    Thiết lập màn hình xác thực Google

    Click vào Save sẽ hiện ra màn hình tạo Client ID.

    Tạo Client ID cho xác thực Google

    Trong phần này chúng ta để ý phần Authorized redirect URIs, đây chính là đường dẫn callback khi mà Google đã xác thực xong sẽ chuyển hướng về đây. Ở đây, chúng ta sử dụng ví dụ laravel-test nên đường dẫn chúng ta sẽ sử dụng là http://laravel.dev/auth/google/callback. Tiếp đó click Create sẽ tạo ra các thông tin để tích hợp xác thực Google.

    Thông tin dùng tích hợp xác thực Google

    Bước 3: Thay đổi bảng users

    Trong ứng dụng Laravel, khi cần xác thực người dùng dùng câu lệnh artisan make:auth để tạo ra các view, route, controller cần thiết (Xem thêm Xác thực người dùng bằng Laravel Authenticaion). Khi đó, bảng users cũng được tạo ra, để lưu thêm các thông tin liên quan đến các mạng xã hội, chúng ta cần thêm các cột provider chứa tên mạng xã hội và provider_id là id của tài khoản mạng xã hội. Chúng ta sẽ sử dụng Laravel Migration để thay đổi database (nên sử dụng vì trong các dự án lớn làm việc nhiều người, sử dụng Laravel Migration giúp quản lý được các phiên bản cấu trúc cơ sở dữ liệu).

    c:\xampp\htdocs\laravel-test>php artisan make:migration alter2_users_table --table=users
    Created Migration: 2017_04_23_152423_alter2_users_table

    alter2 do trong bài Xác thực tài khoản mới đăng ký qua email trong Laravel đã có file alter_users_table. Mở file 2017_04_23_152423_alter2_users_table trong thư mục database/migrations và thêm các đoạn mã tạo hai cột cần thiết:

    <?php
    
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class Alter2UsersTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table('users', function (Blueprint $table) {
                $table->string('provider');
                $table->string('provider_id');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::table('users', function (Blueprint $table) {
                $table->dropColumn('provider');
                $table->dropColumn('provider_id');
            });
        }
    }

    Tiếp theo thực hiện lệnh php artisan migrate để thực hiện các thay đổi.

    c:\xampp\htdocs\laravel-test>php artisan migrate
    Migrated: 2017_04_23_152423_alter2_users_table

    Bước 4: Thiết lập thông số cho Laravel Socialite

    Thiết lập các thông số trong config/service.php với các thông số client id và client secret có được ở bước 2 (các thông tin này đã được bôi mờ, bạn nên thiết lập tài khoản Google riêng):

    <?php
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Third Party Services
        |--------------------------------------------------------------------------
        |
        | This file is for storing the credentials for third party services such
        | as Stripe, Mailgun, SparkPost and others. This file provides a sane
        | default location for this type of information, allowing packages
        | to have a conventional place to find your various credentials.
        |
        */
    
        'mailgun' => [
            'domain' => env('MAILGUN_DOMAIN'),
            'secret' => env('MAILGUN_SECRET'),
        ],
    
        'ses' => [
            'key' => env('SES_KEY'),
            'secret' => env('SES_SECRET'),
            'region' => 'us-east-1',
        ],
    
        'sparkpost' => [
            'secret' => env('SPARKPOST_SECRET'),
        ],
    
        'stripe' => [
            'model' => App\User::class,
            'key' => env('STRIPE_KEY'),
            'secret' => env('STRIPE_SECRET'),
        ],
        'google' => [
            'client_id' => '61159249             go4hovqiohip4h                       content.com',
            'client_secret' => '6xYdUYaf          pqcBpX',
            'redirect' => 'http://laravel.dev/auth/google/callback',
        ],
    ];

    Bước 5: Thêm route và code xử lý xác thực Google.

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

    Route::get('/auth/{provider}', 'SocialAuthController@redirectToProvider');
    Route::get('/auth/{provide}/callback', 'SocialAuthController@handleProviderCallback');

    Do chúng ta tích hợp xác thực các mạng xã hội như Facebook, Google, Twitter nên chúng ta để tham số trong đường dẫn là provider có thể là facebook, google, twitter. Tạo SocialAuthController để xử lý việc xác thực, ghi nhận vào database... bằng lệnh artisan make:controller

    c:\xampp\htdocs\laravel-test>php artisan make:controller SocialAuthController
    Controller created successfully.

    Tiếp đó, thêm code xử lý vào SocialAuthController.php vừa tạo (trong thư mục app\Http\Controllers\SocialAuthController.php):

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use Socialite, Auth, Redirect, Session, URL;
    use App\User;
    
    class SocialAuthController extends Controller
    {
        /**
         * Chuyển hướng người dùng sang OAuth Provider.
         *
         * @return Response
         */
        public function redirectToProvider($provider)
        {
            if(!Session::has('pre_url')){
                Session::put('pre_url', URL::previous());
            }else{
                if(URL::previous() != URL::to('login')) Session::put('pre_url', URL::previous());
            }
            return Socialite::driver($provider)->redirect();
        }  
    
        /**
         * Lấy thông tin từ Provider, kiểm tra nếu người dùng đã tồn tại trong CSDL
         * thì đăng nhập, ngược lại nếu chưa thì tạo người dùng mới trong SCDL.
         *
         * @return Response
         */
        public function handleProviderCallback($provider)
        {
            $user = Socialite::driver($provider)->user();
    
            $authUser = $this->findOrCreateUser($user, $provider);
            Auth::login($authUser, true);
            return Redirect::to(Session::get('pre_url'));
        }
    
        /**
         * @param  $user Socialite user object
         * @param $provider Social auth provider
         * @return  User
         */
        public function findOrCreateUser($user, $provider)
        {
            $authUser = User::where('provider_id', $user->id)->first();
            if ($authUser) {
                return $authUser;
            }
            return User::create([
                'name'     => $user->name,
                'email'    => $user->email,
                'provider' => $provider,
                'provider_id' => $user->id
            ]);
        }
    }

    Kiểm tra kết quả tích hợp xác thực Google bằng Laravel Socialite

    Như vậy, chúng ta đã chuẩn bị xong các bước cần thiết, tiếp theo kiểm tra xem kết quả thực hiện có như mong muốn hay không. Vào đường dẫn đăng nhập Laravel-test http://laravel.dev/login.

    Trang đăng nhập đã tích hợp xác thực bằng Google

    Click vào Đăng nhập bằng Google nó sẽ chuyển hướng đến trang đăng nhập tài khoản Google.

    Chuyển hướng đến màn hình đăng nhập Google

    Khi bạn đăng nhập vào tài khoản của Google, Google sẽ thông báo ứng dụng website tích hợp xác thực Google muốn xem các thông tin tài khoản của bạn.

    Thông báo từ màn hình đăng nhập của Google

    Khi bạn nhấp vào Cho phép, bạn đã đăng nhập vào website thông qua tài khoản của Google. Như vậy, việc tích hợp xác thực bằng Google vào website thông qua Laravel Socialite đã được hoàn thành.

vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!



Khóa học liên quan

Khóa học: Laravel

Xây dựng ứng dụng với Laravel và Vuejs
Số bài học:
Lượt xem: 15804
Đăng bởi: Admin
Chuyên mục: Laravel

Học lập trình Laravel
Số bài học:
Lượt xem: 22790
Đăng bởi: Admin
Chuyên mục: Laravel