Laravel5.4使用socialite实现github登录

By | 2017年9月15日

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’, ‘LoginController@github’); Route::get(‘/github.login’, ‘LoginController@githubLogin’); //这里为刚才的回调路径

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=乱七八糟