Laravel 6.5 と Socialite で Twitter OAuth ログインを実現する

Laravel 6.5 と Socialite で Twitter OAuth ログインを実現する

● 1.Laravel 6.5 のインストール

composer create-project --prefer-dist laravel/laravel my_app

● 2.Laravel 6.5 の初期設定

.env に DB情報を書き込む

varcharのデフォルト文字数を191文字にする

変更ファイル : app\Providers\AppServiceProvider.php

public function boot()
{
    \Illuminate\Support\Facades\Schema::defaultStringLength(191);
}

app.php設定を変更する

変更ファイル : config/app.php

'locale' => 'ja',
'timezone' => 'Asia/Tokyo',

● 3.Laravel 6.5 に Authをインストール

Laravel 標準の認証機能である Auth をインストールします

composer require laravel/ui
php artisan ui vue --auth
php artisan migrate
npm install
npm run dev

● 4.Laravel 6.5 に socialiteをインストール

composer require laravel/socialite

● 5.Twitter Developersから Twitterアプリを登録します

https://dev.twitter.com/index
から「My Apps」-「Create New App」をクリックしてTwitterアプリを登録します

Name: アプリ名
Description: アプリの説明
Website: http://あなたのサーバ名/
Callback URL: http://あなたのサーバ名/auth/twitter/callback

登録後に表示される画面の「Key and Access Tokens」タブから
Consumer Key (API Key) と Consumer Secret (API Secret) をコピーして .env に書き込みます

.env

TWITTER_CLIENT_ID=【consumerkey】
TWITTER_CLIENT_SECRET=【consumersecret】
TWITTER_CALLBACK_URL=http://あなたのサーバ名/auth/twitter/callback

config/services.php に以下を追加

'twitter'=>[
    'client_id'=>env('TWITTER_CLIENT_ID'),
    'client_secret'=>env('TWITTER_CLIENT_SECRET'),
    'redirect'=>env('TWITTER_CALLBACK_URL'),
] ,

● 6.laravelのルーティングを設定

routes/web.php に以下を追加

// Auth Twitter
Route::get('auth/twitter', 'Auth\AuthController@TwitterRedirect');
Route::get('auth/twitter/callback', 'Auth\AuthController@TwitterCallback');
Route::get('auth/twitter/logout', 'Auth\AuthController@getLogout');

// Auth Google
Route::get('auth/google', 'Auth\AuthController@GoogleRedirect');
Route::get('auth/google/callback', 'Auth\AuthController@GoogleCallback');
Route::get('auth/google/logout', 'Auth\AuthController@getLogout');

// Auth Facebook
Route::get('auth/facebook', 'Auth\AuthController@FacebookRedirect');
Route::get('auth/facebook/callback', 'Auth\AuthController@FacebookCallback');
Route::get('auth/facebook/logout', 'Auth\AuthController@getLogout');

● 7コントローラーの設定

app/Http/Controllers/Auth/AuthController.php を以下の内容で新規作成する

<?php
namespace App\Http\Controllers\Auth;

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

class AuthController extends Controller
{

    public function TwitterRedirect()
    {
        return Socialite::driver('twitter')->redirect();
    }

    public function TwitterCallback()
    {
        // OAuthユーザー情報を取得
        $social_user = Socialite::driver('twitter')->user();
        $user = $this->first_or_create_social_user('twitter', $social_user->id, $social_user->name, $social_user->avatar );

        // Laravel 標準の Auth でログイン
        \Auth::login($user);

        return redirect('/home');
    }

    /**
     * ログインしたソーシャルアカウントがDBにあるかどうか調べます
     *
     * @param   string      $service_name       ( twitter , facebook ... )
     * @param   int         $social_id          ( 123456789 )
     * @param   string      $social_avatar      ( https://....... )
     *
     * @return  \App\User   $user
     *
     */
    protected function first_or_create_social_user( string $service_name,
                                                int $social_id, string $social_name, string $social_avatar )
    {
        $user = null;
        $user = \App\User::where( "{$service_name}_id", '=', $social_id )->first();
        if ( $user === null ){
            $user = new \App\User();
            $user->fill( [
                "{$service_name}_id" => $social_id ,
                'name'               => $social_name ,
                'avatar'             => $social_avatar ,
                'password'           => 'DUMMY_PASSWORD' ,
            ] );
            $user->save();
            return $user;
        }
        else{
            return $user;
        }
    }

}

● 8.URLを叩いてログインをテストする

これで準備が整いましたので以下それぞれのurlからログイン出来ることを確認します。

http://あなたのサーバ名/auth/facebook/
http://あなたのサーバ名/auth/twitter/
http://あなたのサーバ名/auth/google/

ログインが完了するとユーザーの情報が表示されるようになります。

どうせならログイン画面に Twitter ログインを追加してみましょう

resources/views/auth/login.blade.php に以下のコードを追加します

                        <div class="form-group row">
                            <div class="col-md-6 offset-md-4">
                                <a href="{{ route('auth.twitter') }}">
                                    <button type="button" class="btn btn-primary"><i class="fab fa-twitter"></i> Twitterアカウントでログインする</button>
                                </a>                                
                            </div>
                        </div>
http://あなたのサーバ名/login

でログイン画面に Twitter ログインが追加されていて、かつ、そこからログインできることを確認します。

● 9.実際のログイン後の実装(ユーザー自動作成)

これでログイン機能自体を実装されていますのでここから先は先ほどのファイル
app/Http/Controllers/Auth/AuthController.php
を編集していきます

ここでは例として初回ログイン時に Laravelのユーザーアカウントを作成するコントローラを作成します。

1. マイグレーションの作成

DBカラム変更パッケージをインストール

composer require doctrine/dbal
php artisan make:migration change_users_table_add_oauth_columns  --table=users

database/migrations/2019_12_xx_xxxxxx_change_users_table_add_oauth_columns.php を編集します

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ChangeUsersTableAddOauthColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->text('avatar')->nullable()->after('remember_token')->comment('アバター画像');
            $table->unsignedBigInteger('twitter_id')->nullable()->after('remember_token')->comment('Twitter ID');
            $table->unsignedBigInteger('facebook_id')->nullable()->after('remember_token')->comment('Facebook ID');
            $table->unsignedBigInteger('github_id')->nullable()->after('remember_token')->comment('GitHub ID');
            $table->unsignedBigInteger('google_id')->nullable()->after('remember_token')->comment('Google ID');
            $table->unsignedBigInteger('yahoo_id')->nullable()->after('remember_token')->comment('Yahoo ID');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('avatar');
            $table->dropColumn('twitter_id');
            $table->dropColumn('facebook_id');
            $table->dropColumn('github_id');
            $table->dropColumn('google_id');
            $table->dropColumn('yahoo_id');
        });
    }
}

2. モデルの fillable を guarded へ変更

    // protected $fillable = [
    //     'name', 'email', 'password',
    // ];

    // guarded
    protected $guarded = ['id', 'created_at', 'updated_at'];

3. マイグレーションの実行

php artisan migrate

これで Twitterでログインをすると、Laravelユーザーとしてログインすることができます。

Laravel 6.5 と Socialite で Twitter OAuth ログインを実現する

2 thoughts on “Laravel 6.5 と Socialite で Twitter OAuth ログインを実現する

  • 2020-05-09 at
    Permalink

    大変参考になりました!
    ありがとうございます。

    1箇所コードが間違っていて、つまずいたのでお知らせします。
    $table->datetime(‘avatar’)->nullable()->after(‘remember_token’)->comment(‘アバター画像’);

    このままだと使えなくて、型を文字列に直したらうまくいきました。

    Reply
    • 2020-12-11 at
      Permalink

      ご指摘ありがとうございます。
      確かに 画像のURLを格納するのに、DATETIME型はおかしいですね。
      修正させていただきます。

      Reply

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です