telenok/socialite

Laravel 封装 OAuth 1 & OAuth 2 库。

v2.0.17 2016-05-27 12:42 UTC

README

Build Status Total Downloads Latest Stable Version Latest Unstable Version License Dependency Status

简介

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 配置文件中,并应使用 facebooktwitterlinkedingooglegithubbitbucket 键,具体取决于您的应用程序需要的提供者。例如

'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 方法时,请务必不要传递任何保留关键字,如 stateresponse_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();