본문 바로가기

개발/Laravel

Laravel Socialite와 SocialiteProvider를 활용한 다중인증 소셜로그인 및 동적 URL 처리

0. 환경

- laravel/socialite v5.1.3

- socialiteproviders/manager v4.0.1

- socialiteproviders/kakao v4.2.2

 

1. Laravel Socialite & Provider 설치

composer require laravel/socialite
composer require socialiteproviders/{$provider}

2. config/services.php 에서 provider 설정

'kakao' => [
        'client_id' => env('KAKAO_CLIENT_ID'),
        'client_secret' => env('KAKAO_CLIENT_SECRET'),
        'redirect' => env('KAKAO_URL'),
    ],

3. route 정의

// Socialite
Route::get('/login/{provider}', [SocialController::class, 'redirect']);
Route::get('/login/{provider}/callback', [SocialController::class, 'Callback']);

4. sociallogin 을 처리하기 위한 컨트롤러 개발

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Socialite;

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

    public function Callback($provider)
    {
        $userSocial = Socialite::driver($provider)->user();

        $users = User::where(['email' => $userSocial->getEmail(), 'provider' => $provider])->first();

        if($users)
        {
            Auth::login($users);
            return redirect('/');
        }
        else
        {
        $user = User::create([
                    'realname'      => $userSocial->getName(),
                    'email'         => $userSocial->getEmail(),
                    'userid'        => $userSocial->getid(),
                    'provider_id'   => $userSocial->getId(),
                    'provider'      => $provider,
                ]);

        $users = User::where(['email' => $userSocial->getEmail(), 'provider' => $provider])->first();
        
        Auth::login($users);
        return redirect('/');
        }
    }
}

5. EventServiceProvider 프로바이더 수정

use SocialiteProviders\Kakao\KakaoExtendSocialite;
use SocialiteProviders\Manager\SocialiteWasCalled;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        SocialiteWasCalled::class => [
            KakaoExtendSocialite::class,
            ...
        ],
        ...
    ];
    
    ...
}

6. config/app.php 에서 provider, aliases 수정

'providers' => [
        /*
         * Laravel Framework Service Providers...
         */
         ...

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        ...
        SocialiteProviders\Manager\ServiceProvider::class,
        ...
    ],
    
    'aliases' => [
        ...
        'Socialite'=> Laravel\Socialite\Facades\Socialite::class,
    ],

7. .env 환경변수 설정 

KAKAO_CLIENT_ID={YOUR_CLIENT_ID}
KAKAO_CLIENT_SECRET=
KAKAO_URL={YOUR_URL}/login/kakao/callback

 

반응형