はじめに

LaravelでLaravel Socialiteを使ってSNS認証の実装を試してみたときのメモ。

Facebookアプリの作成については省略。

インストール

$ composer require laravel/socialite

でインストールしようとしたら以下のエラーとなった。

$ 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)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v5.3.28
    - Conclusion: don't install laravel/framework v5.3.28
    - laravel/socialite v3.0.0 requires illuminate/support ~5.4 -> satisfiable by illuminate/support[v5.4.0, v5.4.9].
    - laravel/socialite v3.0.2 requires illuminate/support ~5.4 -> satisfiable by illuminate/support[v5.4.0, v5.4.9].
    - laravel/socialite v3.0.3 requires illuminate/support ~5.4 -> satisfiable by illuminate/support[v5.4.0, v5.4.9].
    - don't install illuminate/support v5.4.0|don't install laravel/framework v5.3.28
    - don't install illuminate/support v5.4.9|don't install laravel/framework v5.3.28
    - Installation request for laravel/framework (locked at v5.3.28, required as 5.3.*) -> satisfiable by laravel/framework[v5.3.28].
    - Installation request for laravel/socialite ^3.0 -> satisfiable by laravel/socialite[v3.0.0, v3.0.2, v3.0.3].


Installation failed, reverting ./composer.json to its original content.

socialite 3.0.* はlaravel 5.4以上が必要みたいなのでバージョンを指定してインストールした。

$ composer require laravel/socialite "2.0.*"

設定

config/app.php に以下を追加

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    // Other aliases...

    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

config/services.php に以下を追加

'facebook' => [
        'client_id'     => env('FACEBOOK_ID'),
        'client_secret' => env('FACEBOOK_SECRET'),
        'redirect'      => env('FACEBOOK_CALLBACKURL'),
    ],

このようにすると実際の値は.env に持たせることができる。

ルーティング

routes/web.php に以下を追加

// routes/web.php
Route::get('auth/{provider}', 'Auth\AuthController@redirectToProvider');
Route::get('auth/{provider}/callback', 'Auth\AuthController@handleProviderCallback');

コントローラー

app/Http/Controllers/Auth/AuthController.php を作成

<?php

namespace App\Http\Controllers\Auth;

use Socialite;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    /**
     * Redirect the user to the Provider authentication page.
     *
     * @return Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from Provider.
     *
     * @return Response
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();
        dd($user);
    }
}

動作確認

ブラウザから/auth/facebook にアクセスしてFacebookログインできるか確認する。