1. 程式人生 > >laravel5.4使用socialite實現github登入

laravel5.4使用socialite實現github登入

1.安裝laravel5.4

composer create-project laravel/laravel zcms 5.4

2.安裝Socialite

composer require laravel/socialite

3.配置

編輯config/app.php

'providers' => [
    // 其它服務提供者...
    Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite
::class, ]

編輯config/service.php

'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => env('GITHUB_REDIRECT'),
],

4.申請github oauth apps

1.登入github->settings->OAuth Apps
2.填寫Homepage URL(網站域名http://www.zcms.site

),Authorization callback URL(回撥路徑http://www.zcms.site/github/login
3.複製client_id,client_secret到.env檔案

GITHUB_CLIENT_ID=211a7aa4b9c5a3a4c10c
GITHUB_CLIENT_SECRET=2d3174561e440ed887a604f571aff9fa5bd84e44
GITHUB_REDIRECT=http://www.zcms.site/github/login

5.使用

1.新增路由

Route::get('/login', '[email protected]
'
); Route::get('/github.login', '[email protected]'); //這裡為剛才的回撥路徑

2.建立Controller
App\Http\Controllers建立LoginController.php

<?php 

namespace App\Http\Controllers;

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

class LoginController extends Controller
{
    public function github()
    {
        return Socialite::driver('github')->redirect();
    }

    public function githubLogin()
    {
        $user = Socialite::driver('github')->user();
        dd($user);
    }
}

6.見證奇蹟吧

訪問www.zcms.site/login。竟然跳轉到了github,確認之後返回www.zcms.site/github/login?code=亂七八糟