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,
]

数据库

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

2.执行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

创建登陆Controller

php artisan make:controller SocialAuthController

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开发

第三方平台

Facebook Login

打开Facebook开发者页面(https://developers.facebook.com/)

Laravel Socialite总集_第1张图片
facebook-for-devs.png

创建一个Website应用


Laravel Socialite总集_第2张图片
new-app.png

输入应用名和类型,接着跳过Quick Start步骤。


Laravel Socialite总集_第3张图片
app-name.png

点击进入应用设置页面,添加website平台,并加入本地服务器用于测试


Laravel Socialite总集_第4张图片
site-url.png

从该页面取得client_id和client_secret,打开config/services.php,添加:

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

在生产环节中,必须使用env()函数来获取client_id和client_secret

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

Facebook

在windows环境下有可能会遇到**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应该就没什么问题了。

Github

Github的比较简单,登陆github,打开Settings->Developer settings->OAuth applications,

Laravel Socialite总集_第5张图片
github_apps.png

然后创建新应用即可


Laravel Socialite总集_第6张图片
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中加入代码:

Github

完成!

Google

登陆Google开发者,进入Google API Console[https://console.developers.google.com/apis/library],

Laravel Socialite总集_第7张图片
google_api.png

创建凭据:


Laravel Socialite总集_第8张图片
google_keys.png

用于本地测试需要额外的步骤:
1.登陆(https://admin.google.com/) [Google Admin console]
2.点击Applications > Others Google services > Google+ > avance settings.
3.激活API 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中加入代码:

Google

完成

你可能感兴趣的:(Laravel Socialite总集)