1、简介
除了传统的基于表格的登录认证,Laravel 还使用 Laravel Socialite
提供了一个优雅的流式接口,用于通过 Facebook、Twitter、Google、
我们不接受新的适配器。
社区驱动的其他平台的适配器罗列在 Socialite提供者 网站上。
要使用社会化登录,需要在 composer.json
文件中添加依赖:
composer require laravel/socialite
之后运行 composer update
安装依赖。
2、配置
安装完社会化登录库后,在配置文件 config/app.php
中注册 Laravel\Socialite\SocialiteServiceProvider
:
'providers' => [ // 其它服务提供者... Laravel\Socialite\SocialiteServiceProvider::class, ],
还要在 app
配置文件中添加 Socialite门面到
aliases
数组:
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
你还需要为应用使用的 OAuth 服务添加认证信息,这些认证信息位于配置文件 config/services.php
,而且对应key为 facebook
、 twitter
、
、 google
、 github
或 bitbucket
,配置哪些 key 取决于应用需要的提供者。例如:
'github' => [ 'client_id' => 'your-github-app-id', 'client_secret' => 'your-github-app-secret', 'redirect' => 'http://your-callback-url', ],
3、基本使用
接下来,准备好认证用户!你需要两个路由:一个用于重定向用户到 OAuth 提供者,另一个用户获取认证后来自提供者的回调。我们使用 Socialite
门面访问 Socialite :
<?php namespace App\Http\Controllers\Auth; use Socialite; class AuthController extends Controller { /** * 将用户重定向到Github认证页面 * * @return Response */ public function redirectToProvider() { return Socialite::driver('github')->redirect(); } /** * 从Github获取用户信息. * * @return Response */ public function handleProviderCallback() { $user = Socialite::driver('github')->user(); // $user->token; } }
redirect
方法将用户发送到 OAuth 提供者, user
方法读取请求信息并从提供者中获取用户信息,在重定向用户之前,你还可以在请求上使用 scope
方法设置”作用域”,该方法将会重写已存在的所有作用域:
return Socialite::driver('github') ->scopes(['scope1', 'scope2'])->redirect();
当然,你需要定义路由到控制器方法:
Route::get('auth/github', 'Auth\AuthController@redirectToProvider'); Route::get('auth/github/callback', 'Auth\AuthController@handleProviderCallback');
很多OAuth提供者在重定向请求中支持可选参数,要在请求中包含可选参数,可以通过一个关联数组调用 with
方法:
return Socialite::driver('google') ->with(['hd' => 'example.com'])->redirect();
使用 with
方法的时候,注意不要传递保留关键字作为数组的key,例如 state
或 response_type
。
获取用户信息
有了用户实例之后,就可以获取更多用户详情:
$user = Socialite::driver('github')->user(); // OAuth Two Providers $token = $user->token; $refreshToken = $user->refreshToken; // not always provided $expiresIn = $user->expiresIn; // OAuth One Providers $token = $user->token; $tokenSecret = $user->tokenSecret; // All Providers $user->getId(); $user->getNickname(); $user->getName(); $user->getEmail(); $user->getAvatar();