nikitarudenko / socialite-plus-vk
Laravel 的 OAuth 1 & OAuth 2 库包装器。
Requires
- php: >=5.4.0
- guzzlehttp/guzzle: ~5.0|~6.0
- illuminate/contracts: ~5.0
- illuminate/http: ~5.0
- illuminate/support: ~5.0
- league/oauth1-client: ~1.0
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2016-12-06 11:39:30 UTC
README
简介
Laravel Socialite 提供了一种流畅的接口,用于 OAuth 认证 Facebook、Twitter、Google、LinkedIn、GitHub 和 Bitbucket。它处理了几乎所有你讨厌编写的社交认证代码。
许可证
Laravel Socialite 是开源软件,受 MIT 许可证 的许可。
官方文档
除了典型的基于表单的认证外,Laravel 还提供了一个简单方便的方式,使用 Laravel Socialite 通过 OAuth 提供商进行认证。Socialite 当前支持 Facebook、Twitter、LinkedIn、Google、GitHub 和 Bitbucket 的认证。
要开始使用 Socialite,请将其添加到您的 composer.json
文件中作为依赖项
composer require laravel/socialite
配置
安装 Socialite 库后,在您的 config/app.php
配置文件中注册 Laravel\Socialite\SocialiteServiceProvider
'providers' => [
// Other service providers...
Laravel\Socialite\SocialiteServiceProvider::class,
],
此外,将 Socialite
门面添加到您的 app
配置文件中的 aliases
数组中
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
您还需要添加应用程序使用的 OAuth 服务的凭证。这些凭证应放在您的 config/services.php
配置文件中,并应使用键 facebook
、twitter
、linkedin
、google
、github
或 bitbucket
,具体取决于应用程序需要的提供程序。例如
'github' => [
'client_id' => 'your-github-app-id',
'client_secret' => 'your-github-app-secret',
'redirect' => 'http://your-callback-url',
],
基本用法
接下来,您就可以认证用户了!您需要两个路由:一个用于将用户重定向到 OAuth 提供商,另一个用于接收认证后的回调。我们将通过 Socialite
门面访问 Socialite
<?php
namespace App\Http\Controllers;
use Socialite;
class AuthController extends Controller
{
/**
* Redirect the user to the GitHub authentication page.
*
* @return Response
*/
public function redirectToProvider()
{
return Socialite::driver('github')->redirect();
}
/**
* Obtain the user information from 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();
检索用户详细信息
一旦您有了用户实例,您就可以获取更多有关用户的信息
$user = Socialite::driver('github')->user();
// OAuth Two Providers
$token = $user->token;
// OAuth One Providers
$token = $user->token;
$tokenSecret = $user->tokenSecret;
// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();