Laravel使用github授权登录
一、首先在github注册账号 然后https://github.com/settings/applications/1267636这里填写相关资料获取到key和secret
二、在.env配置文件写相关配置:
GITHUB_KEY=Client ID GITHUB_SECRET=Client Secret GITHUB_REDIRECT_URI=回调地址
三、配置相关路由
//github Route::namespace('Auth')->prefix('auth')->group(function (){ Route::get('github','SocialitesController@github'); Route::get('callback','SocialitesController@callback'); });
四、在这个网站 https://packagist.org/ 搜索 socialiteproviders/manager
确保已经安装composer
在项目根目录执行
composer require socialiteproviders/manager
composer require socialiteproviders/github
然后在config/app .php
添加providers:
添加aliases:
五、新建控制器
php artisan make:controller Auth/SocialitesConteoller
示例代码:
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Socialite; use App\User; use Auth; class SocialitesController extends Controller { //用户点击跳转授权页面 public function github() { return Socialite::driver('github')->redirect(); } //用户授权后,回调页面 public function callback() { $info = Socialite::driver('github')->user(); $user=User::where('email',$info->email)->first(); $data = [ 'name'=>$info->nickname, 'username'=>$info->nickname, 'email'=>$info->email, 'github_name'=>$info->nickname, 'password'=>bcrypt('123456789'), 'avatar'=>$info->avatar ]; if(empty($user)){ $user=User::create($data); } Auth::login($user); return Redirect()->guest('/'); } }