larastarscn/socialite

laravel socialite 扩展,支持中文

v0.0.2 2016-09-27 01:16 UTC

This package is not auto-updated.

Last update: 2024-09-28 19:52:43 UTC


README

License Dependency Status

简介

本包基于 Laravel\Socialite 扩展,它提供了一个直观的接口,用于与 Facebook、Twitter、Google、LinkedIn、GitHub 和 Bitbucket 进行 OAuth 认证。它处理了您可能不想编写的大多数社交认证模板代码。为了支持中国的流行应用,我们扩展了微信、QQ 和微博。

其他平台的适配器列在社区驱动的 Socialite Providers 网站上。

安装

要开始使用 Socialite,请将以下依赖添加到您的 composer.json 文件中

composer require larastarscn/socialite

配置

安装 Socialite 库后,在您的 config/app.php 配置文件中注册 Larastarscn\Socialite\SocialiteServiceProvider

'providers' => [
    // Other service providers...

    Larastarscn\Socialite\SocialiteServiceProvider::class,
]

同时,将 Socialite 门面添加到 app 配置文件中的 aliases 数组中

'Socialite' => Laravel\Socialite\Facades\Socialite::class

您还需要添加应用程序使用的 OAuth 服务的凭据。这些凭据应放置在您的 config/services.php 配置文件中,并使用键 facebooktwitterlinkedingooglegithubbitbucketwechatqqweibo,具体取决于应用程序所需的提供者。例如

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