Laravel Socialite總集

安裝socialite包

composer require laravel/socialite

修改config/app.php

'providers' => [
  // Other service providers...
  Laravel\Socialite\SocialiteServiceProvider::class,
],

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

數(shù)據(jù)庫

  1. 修改database/migrations/create_users_table.php,或者添加新的migration進行修改
    $table->string('email')->unique()->nullable();

2.執(zhí)行php artisan make:model SocialAccount -m生成Model和migrations
修改create_social_accounts_table:

Schema::create('social_accounts', function (Blueprint $table) {
    $table->integer('user_id');
    $table->string('provider_user_id');
    $table->string('provider');
    $table->timestamps();
});

修改SocialAccount類

namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialAccount extends Model
{
    protected $fillable = ['user_id', 'provider_user_id', 'provider'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

運行php artisan migrate

創(chuàng)建登陸Controller

php artisan make:controller SocialAuthController

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Socialite;

class SocialAuthController extends Controller
{
    public function redirect($provider)
    {
        return Socialite::driver($provider)->redirect();   
    }   

    public function callback($provider)
    {
       $user = $this->createOrGetUser(Socialite::driver($provider)->user(), $provider);
       Auth::login($user);
       return redirect()->to('/home'); 
    }

    private function createOrGetUser(ProviderUser $providerUser, $provider)
    {
      $account = SocialAccount::whereProvider($provider)
        ->whereProviderUserId($providerUser->getId())
        ->first();
      if ($account) {
        return $account->user;
      } else {
        $account = new SocialAccount([
          'provider_user_id' => $providerUser->getId(),
          'provider' => $provider
        ]);
        $email = $providerUser->getEmail();
        if ($email) {
          $user = User::whereEmail($providerUser->getEmail())->first();
          if (!$user) {
            $user = User::create([
              'email' => $providerUser->getEmail(),
              'name' => $providerUser->getName(),
              'password' => bcrypt('123456')
            ]);
          }
      } else {
        $user = User::create([
          'name' => $providerUser->getName(),
          'password' => bcrypt('123456')
        ]);
      }
      $account->user()->associate($user);
      $account->save();
      return $user;
    }
  }
}

路由

route.php(<=5.2) 或者web.php(5.3) 中加入

Route::get('/{provider}/redirect', 'SocialAuthController@redirect')->name('redirect');
Route::get('/{provider}/callback', 'SocialAuthController@callback')->name('callback');

至此,準備工作都完成了,接下來進行各個平臺的oauth開發(fā)

第三方平臺

Facebook Login

打開Facebook開發(fā)者頁面(https://developers.facebook.com/)

facebook-for-devs.png

創(chuàng)建一個Website應(yīng)用


new-app.png

輸入應(yīng)用名和類型,接著跳過Quick Start步驟。


app-name.png

點擊進入應(yīng)用設(shè)置頁面,添加website平臺,并加入本地服務(wù)器用于測試


site-url.png

從該頁面取得client_id和client_secret,打開config/services.php,添加:

'facebook' => [
    'client_id' => '690344774435367',
    'client_secret' => 'ebc50d3fd1d2f7286e02d247e5751ef4',
    'redirect' => 'http://localhost:8000/facebook/callback',
],

在生產(chǎn)環(huán)節(jié)中,必須使用env()函數(shù)來獲取client_id和client_secret

resources/views/auth/login.blade.php中加入代碼:

<a href="route('redirect', 'facebook')">Facebook</a>

在windows環(huán)境下有可能會遇到**Error: [cURL error 60: SSL certificate in Laravel 5 while Facebook authentication] **
可以下載 cacert.pemhttps://gist.github.com/VersatilityWerks/5719158/download,然后解壓拿到cacert.pem
放到任意位置,然后修改文件php.inicurl.cainfo = "path_to_cert\cacert.pem", 這里path_to_cert就是放置cacert.pem的路徑

這樣使用Facebook應(yīng)該就沒什么問題了。

Github

Github的比較簡單,登陸github,打開Settings->Developer settings->OAuth applications

github_apps.png

然后創(chuàng)建新應(yīng)用即可


github_keys.png

然后回到Laravel,只需在
config/services.php中添加:

'github' => [
    'client_id' => '690344774435367',
    'client_secret' => 'ebc50d3fd1d2f7286e02d247e5751ef4',
    'redirect' => 'http://localhost:8000/github/callback',
],

resources/views/auth/login.blade.php中加入代碼:

<a href="route('redirect', 'github')">Github</a>

完成!

Google

登陸Google開發(fā)者,進入Google API Console[https://console.developers.google.com/apis/library],

google_api.png

創(chuàng)建憑據(jù):


google_keys.png

用于本地測試需要額外的步驟:
1.登陸(https://admin.google.com/) [Google Admin console]
2.點擊Applications > Others Google services > Google+ > avance settings.
3.激活A(yù)PI Google+

然后回來Laravel
config/services.php中添加:

'google' => [
    'client_id' => '763269637355-dj6d21427p78r17l4f263lq84p23as4q.apps.googleusercontent.com',
    'client_secret' => 'ebc50d3fd1d2f7286e02d247e575xxxx',
    'redirect' => 'http://localhost:8000/google/callback',
],

resources/views/auth/login.blade.php中加入代碼:

<a href="route('redirect', 'google')">Google</a>

完成

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容