raymondwilkinson / socialite
Laravel围绕OAuth 1 & OAuth 2库的包装器。
Requires
- php: >=5.4.0
- guzzlehttp/guzzle: ~6.0
- illuminate/contracts: ~5.4
- illuminate/http: ~5.4
- illuminate/support: ~5.4
- league/oauth1-client: ~1.0
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0|~5.0
This package is not auto-updated.
Last update: 2024-09-14 18:58:46 UTC
README
简介
Laravel Socialite提供了一个用于与Facebook、Twitter、Google、LinkedIn、GitHub和Bitbucket进行OAuth身份验证的表达式丰富的流畅接口。它处理了您不想编写的几乎所有的样板社交身份验证代码。
我们不接受新的适配器。
许可证
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\Auth; 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();
当使用with
方法时,请小心不要传递任何保留关键字,如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();