Laravel使用github授权登录

时间:2020-05-29
本文章向大家介绍Laravel使用github授权登录,主要包括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:

'providers' => [
    SocialiteProviders\Manager\ServiceProvider::class,
],

添加aliases:

'aliases' => [ 
    'Socialite' => Laravel\Socialite\Facades\Socialite::class, 
],

五、新建控制器

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('/');
    }
}

  

原文地址:https://www.cnblogs.com/guoyachao/p/12989226.html