安裝 Laravel 6.x LTS 及 Authentication
參考官方網站步驟建立
composer create-project --prefer-dist laravel/laravel facebookAuth "6.*"
composer require laravel/ui "^1.0" --dev
php artisan ui vue --auth
npm install && npm run dev
安裝 laravel/socialite
composer require laravel/socialite
修改 config/app.php
# providers 加入
Laravel\Socialite\SocialiteServiceProvider::class,
# aliases 加入
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
修改 config/services.php,加入 Google
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],
建立 SocialAuthGoogleController 控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialGoogleAccountService;
class SocialAuthGoogleController extends Controller
{
/**
* Create a redirect method to google api.
*
* @return void
*/
public function redirect()
{
return Socialite::driver('google')->redirect();
}
/**
* Return a callback method from google api.
*
* @return callback URL from google
*/
public function callback(SocialGoogleAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect()->to('/home');
}
}
修改 route/web.php 新增
Route::get('/redirect', 'SocialAuthGoogleController@redirect');
Route::get('/callback', 'SocialAuthGoogleController@callback');
建立 Model 及 修改相關檔案
php artisan make:model SocialGoogleAccount -m
修改 app/SocialGoogleAccount.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialGoogleAccount extends Model
{
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
修改 create_social_google_accounts_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSocialGoogleAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('social_google_accounts', function (Blueprint $table) {
$table->integer('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('social_google_accounts');
}
}
修改完成後執行 php artisan migrate:refresh 將資料庫建立起來。
新增 app/Services 目錄及 SocialGoogleAccountService.php
<?php
namespace App\Services;
use App\SocialGoogleAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialGoogleAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialGoogleAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialGoogleAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(rand(1, 10000)),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
修改 login 視圖,新增一個按鈕
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<a href="{{url('/redirect')}}" class="btn btn-danger">Login with Google</a>
</div>
</div>
</div>
</div>
到 https://console.developers.google.com/ 建立 OAuth2.0 用戶端 ID 取得 APP_ID及 APP_SECRET,並修改 .env 檔案,新增 Google 相關設定
GOOGLE_CLIENT_ID= 到 https://console.developers.google.com/ 取得
GOOGLE_CLIENT_SECRET= 到 https://console.developers.google.com/ 取得
GOOGLE_REDIRECT=https://localhost/callback
測試
成品同步放在我的 GitHub 上.