Laravel Socialite - Google 第三方登入

2020/12/18閱讀時間約 5 分鐘
GCP:
API和服務 -> 資訊主頁 -> +啟用API和服務
搜尋google+ 啟用:
設定 OAuth 同意畫面:
選擇外部後,開始填寫資料:
建立憑證:
假如有多個應用程式平台,如網頁、app,都要各自建立OAuth用戶。

已授權的重新導向URI:
使用者透過 Google 完成驗證程序之後,系統就會將他們重新導向這個路徑,這邊是callback,稍後看程式碼就知道了。
ex: http://yourdomain/google/auth/callback

程式的部分:


1. 安裝Socialite
$ composer require laravel/socialite
2. 設定
config/services.php加入
'google' => [
  'client_id' => env('GOOGLE_CLIENT_ID'),
  'client_secret' => env('GOOGLE_CLIENT_SECRET'),
  'redirect' => 'http://yourdomain/google/auth/callback',
],
redirect: 使用者透過 Google 完成驗證程序之後,系統就會將他們重新導向這個路徑,跟上述的一樣。
.env中記得設定 GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=xxx
3. Route(web.php)
因為會用到session,要走web middleware。
4. Controller
如果要帶入額外參數,可以這樣:

Route::get('/google/auth/{my_param}', ...);

public function redirectToProvider($my_param){
  return Socialite::driver('google')
->with(['state' => 'my_param='. $my_param])->redirect();
}
然後在callback接:
public function handleProviderCallback(){
  $state = request()->input('state');
parse_str($state, $result);
$my_param = $result['my_param'];
}

Demo:
首先url輸入: http://yourdomain/google/auth
之後就會導向google認證頁面:
登入google之後,會自動redirect to callback:
http://yourdomain/google/auth/callback
這邊只能拿到基本資訊,比較有用的就是姓名、大頭貼、email。
可啟用Google People API取得更多資料,如性別、生日、地址等等! 在OAuth同意畫面的範圍,就可以勾選透過People API想存取的user data。

Note:
如果看到accounts.google.com redirected you too many times這個瀏覽器錯誤,主要是因為要多帶額外的參數到callback,才會發生這個錯誤,本範例的code沒有帶參數所以不會發生,解法是要改callback的route path:
原本是這樣:
Route::get('/google/auth', ...);
Route::get('/google/auth/callback', ...);
改為:
Route::get('/google/authCallback', ...);
別忘了在GCP -> API和服務 -> 憑證 ->已授權的重新導向URI,這邊也要改!
為什麼會看到廣告
20會員
161內容數
留言0
查看全部
發表第一個留言支持創作者!